I'm implementing a Java version of the game Mastermind.
My version uses numbers to represent colors, for example 2315. This function compares a string of numbers to the secret code the object stored. It works, but I'm wondering if this could be done in a more elegant way.
public Answer evaluate(String guess) {
boolean[] codeUsed = new boolean[code.length()];
boolean[] guessUsed = new boolean[guess.length()];
int correct = 0;
int match = 0;
// Compare correct color and position
for (int i = 0; i < code.length(); i++) {
if (code.charAt(i) == guess.charAt(i)) {
correct++;
codeUsed[i] = guessUsed[i] = true;
}
}
// Compare matching colors for "pins" that were not used
for (int i = 0; i < code.length(); i++) {
for (int j = 0; j < guess.length(); j++) {
if (!codeUsed[i] && !guessUsed[j] && code.charAt(i) == guess.charAt(j)) {
match++;
codeUsed[i] = guessUsed[j] = true;
break;
}
}
}
return new Answer(guess, correct, match, guess.length() - correct - match);
}
guessalso? And what isguess.length() - correct - match? – abuzittin gillifirca Jan 23 at 16:22wrongpins. – Sven Jan 23 at 16:34