I have this code to implement logic for the Bulls and Cows game:
Bulls and Cows is a 2 player game. The computer thinks of a number, while the other player tries to guess it.
The number to be guessed must be a 4-digit number, using only digits from 1 - 9 and between the numbers 1000 and 9999, each digit at most once. e.g. 1234 is valid, 0123 is not valid, 9877 is not valid, 9876 is valid.
For every guess that the player makes, he gets 2 values : the number of bulls and the number of cows.
1 bull means the guess contains and the target number have 1 digit in common, and in the correct position.
1 cow means the guess and the target have 1 digit in common, but not in correct position.
Let the target be 1234. Guessing 4321 will give 0 bulls and 4 cows. 3241 will give 1 bull and 3 cows
When I try it, I get the wrong output:
Enter a Number :
3054
Number Generated by Computer: 2441
Input was : 3054
0 bulls and 2 cows
There should be 1 cow instead of 2 cows.
What is wrong with the code, and how do I fix it? What changes should I make in my conditional statements to get the accurate answer? please suggest
What I have tried:
import java.util.*;
public class Bulls_Cows
{
int num,bulls,cows,random_int,temp,temp_rand,temp1_rand;
static int digit[] = new int[4];
static int digit_rand[] = new int[4];
public void input()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Number : ");
num = sc.nextInt();
}
public void checkBullorCow()
{
temp = num;
random_int = (int)(Math.random()*9000+1000);
temp_rand = random_int;
temp1_rand = random_int;
for(int i=0;i<4;i++)
{
digit[i]=temp/(int)Math.pow(10,i)%10;
digit_rand[i]=temp_rand/(int)Math.pow(10,i)%10;
}
for (int j = 0; j < digit.length; j++)
{
if (digit[j] == digit_rand[j])
bulls++;
for (int k = 0; k < digit_rand.length; k++)
{
if (k!=j&&digit[j]==digit_rand[k])
cows++;
}
}
}
public void output()
{
System.out.println("Number Generated by Computer: "+temp1_rand);
System.out.println("Input was : "+num);
System.out.println(bulls+" bulls and "+cows+" cows");
}
public static void main()
{
Bulls_Cows ob = new Bulls_Cows();
ob.input();
ob.checkBullorCow();
ob.output();
}
}