Created
January 17, 2022 04:51
-
-
Save BenDMyers/b51cef126e496c87fcaeea7253023509 to your computer and use it in GitHub Desktop.
RWC Wordle Validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const CORRECT = 'correct'; | |
const OUT_OF_PLACE = 'out of place'; | |
const WRONG = 'wrong'; | |
/** | |
* Determines which letters in a given guess are correct, which ones are out of place, and which ones are invalid and returns emoji string | |
* @param {string} guess five-letter guess (presumes the guess has already been through other formatting validations like length and valid characters) | |
* @param {string} solution the target word the player is trying to guess | |
* @returns {string} emoji sequence | |
*/ | |
function validateWordleGuess(guess, solution) { | |
/** | |
* @type {{letter: string, state: CORRECT | OUT_OF_PLACE | WRONG}[]} | |
*/ | |
const guessedLetters = guess | |
.split('') | |
.map(letter => ({letter, state: WRONG})); | |
/** | |
* @type {{letter: string, includedInGuess: boolean}[]} | |
*/ | |
const solutionLetters = solution | |
.split('') | |
.map(letter => ({letter, includedInGuess: false})); | |
// First pass: correct letters in the correct place | |
for (let i = 0; i < guessedLetters.length; i++) { | |
if (guessedLetters[i].letter === solutionLetters[i].letter) { | |
guessedLetters[i].state = CORRECT; | |
solutionLetters[i].includedInGuess = true; | |
} | |
} | |
// Second pass: correct letters in the wrong places | |
for (let i = 0; i < guessedLetters.length; i++) { | |
if (guessedLetters[i].state === CORRECT) { | |
continue; | |
} | |
const letterFoundElsewhere = solutionLetters | |
.find((solutionLetter) => { | |
const matchesLetter = solutionLetter.letter === guessedLetters[i].letter; | |
return matchesLetter && !solutionLetter.includedInGuess; | |
}); | |
if (letterFoundElsewhere) { | |
guessedLetters[i].state = OUT_OF_PLACE; | |
letterFoundElsewhere.includedInGuess = true; | |
} | |
} | |
const emojis = guessedLetters.map(guessedLetter => { | |
switch (guessedLetter.state) { | |
case CORRECT: | |
return '🟩'; | |
case OUT_OF_PLACE: | |
return '🟨'; | |
case WRONG: | |
default: | |
return '⬛'; | |
} | |
}); | |
return emojis.join(''); | |
} | |
console.log(validateWordleGuess('reads', 'fudge')); | |
console.log(validateWordleGuess('lodge', 'fudge')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment