Coding Games and Programming Challenges to Code Better
Send your feedback or ask for help here!
In the classic code-breaking game of Bulls and Cows, your opponent chooses a 4-digit secret number, and you need to guess it. After each guess, your opponent tells you how many “bulls” and how many “cows” are in your guess, interpreted as:
Each bull indicates a digit in your guess that exactly matches the value and position of a digit in your opponent’s secret number.
Each cow indicates a digit in your guess that matches the value of a digit in your opponent’s secret number, but is in the wrong position.
So for example, if the secret number is 1234 and you guess 5678, your guess has 0 bulls and 0 cows. However, if you guess 2324 then your guess has 1 bull (the 4) and 2 cows (one of the 2s, and the 3.)
You will be given a series of guesses along with the number of bulls and cows in each guess. Your job is to determine the secret number based on the given information.
NOTE: This version of the game deviates from the classic Bulls and Cows rules in that digits may be repeated any number of times in the secret number.
It will be easier to help you if you tell us what you understood, what you tried, etc.
General tips for this problem:
Bulls should be easy to count, just zip/compare.
Also, it’s easier to count both bulls/cows together than cows alone.
And then you substract bulls to get cows alone.
Write few examples and try to find a way to count bulls/cows together with basic observations.
This is my approach:- I can find no of bulls & cows. But i am not able to figure out how to get the secret number
class Solution {
public String getHint(String secret, String guess) {
int[] map = new int[10];
int n = secret.length();
int bulls =0, cows =0;
for(char c : secret.toCharArray()){
map[c-'0']++;
}
for(char c : guess.toCharArray()){
if(map[c-'0']-- >0)
cows++;
}
for(int i=0; i<n; i++){
if(secret.charAt(i) == guess.charAt(i))
bulls++;
}
return String.valueOf(bulls)+"A"+String.valueOf(cows-bulls)+"B";
}
}
Ok so now all you have to do is to check all strings from 0000 to 9999 and find the one that matches all the bulls/cows given.