tmgunternet
BAN USERI think depending on how the interviewer expects the answer to be returned, we could have a case where the Solution is "BGRR" and the guess is "RRRR". In this case, it might be better to return "Location : 2" and "Color : 0" since we've already guessed the correct two "R" positions. In that case, pre-process first and then loop for the color count:
public static String validateGuess(String solution, String guess) {
if (solution == null || guess == null) return null;
if (solution.length() < 4 || solution.length() > 4 || guess.length() < 4 || guess.length() > 4) return null;
int locationCount = 0; // count of correct color in the correct location
int colorCount = 0; // count of correct color in the incorrect location
if (guess.equalsIgnoreCase(solution)) return "Location: " + locationCount + " | Color: " + colorCount;
boolean[] correctGuesses = new boolean[solution.length()];
for(int i = 0; i < guess.length(); i++) {
char currentChar = guess.charAt(i);
if (solution.indexOf(currentChar) != -1) {
if (currentChar == solution.charAt(i)) {
locationCount++;
correctGuesses[i] = true;
}
}
}
// now that we know all the correct guesses, calculate the color count:
for(int i = 0; i < guess.length(); i++) {
char currentChar = guess.charAt(i);
int index = solution.indexOf(currentChar);
if (index != -1) {
if(!correctGuesses[index]) {
colorCount++;
}
}
}
return "Location: " + locationCount + " | Color: " + colorCount;
}
Quick solution i wrote up in Java
- tmgunternet April 29, 2016