Reputation: 130
I'm working on a Wordle clone, and I'm having an issue with comparing the user input with the correct word.
For anybody unfamiliar with the verification process of Wordle; the user inputs a 5 letter word to be compared to the actual answer. If the letter is in the same position as the correct word, it returns a green value. If the letter position is incorrect, but the letter is in the word, return a yellow value. If the letter is not in the word, return a grey value.
My problem arises when I try to verify a word with a double letter, and the second letter is the correct word. Because I'm iterating through the word index-by-index, the letter is being categorised as yellow incorrectly.
The correct answer for this is CODES.
The first E gets verified as wrong position, correct letter. The second E is in the correct position, therefore the first E should not return yellow, but grey instead.
This is the code I've written below to verify the letter.
let x = input.value().toUpperCase();
let y = correctWord.toUpperCase();
for (let i = 0; i < 5; i++) {
if (y.includes(x[i])) {
if (y[i] == x[i]) {
return green;
} else {
return yellow;
}
} else {
return grey;
}
}
Is there an efficient way to fix this?
Try the demo below: https://wordleclone.butterchoke.repl.co/
The correct word is printed onto the console. You can change the word with
correctWord = "WORD OF YOUR CHOICE";
in the console.
Upvotes: 0
Views: 502
Reputation: 386736
You could take two loops and replace found letters of the word to omit finding the same, but already consumed letter.
function check(input, wordle) {
const
letters = Array.from(input.toUpperCase()),
word = Array.from(wordle.toUpperCase()),
result = Array(5).fill('');
for (let i = 0; i < 5; i++) {
if (letters[i] === word[i]) {
result[i] = 'green',
word[i] = '';
letters[i] = '';
}
}
for (let i = 0; i < 5; i++) {
if (!letters[i]) continue;
const index = word.indexOf(letters[i]);
if (index !== -1) {
result[i] = 'yellow',
word[index] = '';
}
}
return result;
}
console.log(check('eeege', 'green'));
Upvotes: 0