import java.util.*;
/**
* Created by Mridul on 10/17/15.
*/
public class CowsAndBulls {
private final int[] secretNumber;
private int[] guessNumber;
private List<String> guesses;
private int size;
private static final int DEFAULT_SIZE=4;
private int getSize(){
if(size==0) {
return DEFAULT_SIZE;
}else{
return size;
}
}
private void setSize(int size){
this.size = size;
}
public int[] getSecretNumber(){
return secretNumber;
}
CowsAndBulls(){
secretNumber=populateSecretNumber();
guessNumber=new int [getSize()];
Arrays.fill(guessNumber,0);
guesses=new ArrayList<>();
}
private int[] populateSecretNumber(){
Random rand=new Random();
int size=getSize();
int[] number= new int[size];
for(int i=0;i<size;i++){
number[i]= rand.nextInt(9);
}
return number;
}
public void verifyGuess(String guess){
try {
int iguess = Integer.parseInt(guess);
int len = guess.length();
int remainder = 0;
while (len > 0) {
guessNumber[--len] = iguess % 10;
iguess = iguess / 10;
}
computeCowsAndBulls();
}catch (NumberFormatException nfe){
System.out.println("Please enter a valid number");
}
}
private void computeCowsAndBulls(){
int cows=0;
int bulls=0;
for(int i=0; i<guessNumber.length;i++){
for(int j=0;j<secretNumber.length;j++){
if(guessNumber[i]==secretNumber[j]){
//if indexes are same then bulls
if(i==j) {
++bulls;
}else {
++cows;
}
}
}
}
System.out.printf("%d bulls and %d cows\n", bulls, cows);
}
public static void main(String... args){
CowsAndBulls instance =new CowsAndBulls();
do {
System.out.println("Starting Cows and Bulls game!");
System.out.println("Please type EXIT to quit the game anytime!");
System.out.println("Please type REVEAL to show the 4 digit number anytime!");
System.out.println("Please start guessing the 4 digit number : ");
Scanner scanner = new Scanner(System.in);
String currentGuess = scanner.next();
if(currentGuess.equalsIgnoreCase("EXIT")){
System.out.println("Thanks for playing the game!");
System.exit(0);
}else if(currentGuess.equalsIgnoreCase("REVEAL")){
System.out.println("The Secret number is : "
+ Arrays.toString(instance.getSecretNumber()));
System.out.println("Thanks for playing the game!");
System.exit(0);
}
else {
instance.verifyGuess(currentGuess);
}
}while(true);
}
}
Sunday, October 18, 2015
Cows and Bulls Game
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment