I am learning Java and in the process I am writing a Word Guess game.
Now mine problem is the following:
Assume the word to guess is “lingo”. And assume “oodle” is a word you suggested.
On processing your guess, the following should be output:
Correct Letters: none
Wrong Position Letters: ‘o’ at first position, ‘l’ at fourth position
Note that the second ‘o’ should not be mentioned as a letter in the wrong position, as we already have reported an ‘o’ prior to that. So if you enter ‘ooooo’, only the last letter should be highlighted as it is in the correct position, and if you enter ‘ooooz’, only the first letter should be highlighted, and not the other ‘o’s.
I have tried some solutions but all seem to fail. I know there is a smart/not so complex way to do this. So could anyone help me with that?
The code:
// / Indicates whether a letter has been accounted for
// / while highlighting letters in the guess that are not
// / in the correct position
private Boolean[][] marked = new Boolean[WordLength][5];
// / Holds which all letters have been solved so far
private Boolean[][] solved = new Boolean[WordLength][6];
public void CheckLetters() {
for (int j = 0; j < currentAttempt; j++) {
tempWord = list.get(j); //The guessed words
for (int i = 0; i < WordLength; i++) {
if (tempWord.charAt(i) == CurrentPuzzleWord.charAt(i)) {
solved[i][j] = true; //CurrentPuzzleWord is the string with the hidden word
} else if (CurrentPuzzleWord.indexOf(tempWord.charAt(i)) != -1) {
marked[i][j] = true;
}
}
}
So you are going to want to do multiple checks.
The first thing you want to check, obviously, is for letters that are a match and in the right position. So take the oracle string and the user input string and compare them character by character, noting the ones that are correct.
You will then need to do a second check for letters that are correct but in the wrong position. To do this, first take the correct letters from the previous check out of the running. Then for each letter in the input string that matches a letter in the oracle string, note the match and remove it from the rest of the check. Continue this until the entire input string has been looked through.
Combine the results of the two checks and output them to the user.
I am not sure how you want to display the results to the user, but you now have the arraylist
matchwhich corresponds to the positions in oracle/input that are completely correct and the arraylistclosewhich corresponds to the positions in oracle/input such that the letter appears somewhere, but not at that position.