Skip to content

Instantly share code, notes, and snippets.

@chico
Created March 2, 2022 20:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chico/30a01e99400feba3dd2b585e29ad427d to your computer and use it in GitHub Desktop.
Save chico/30a01e99400feba3dd2b585e29ad427d to your computer and use it in GitHub Desktop.
Wordle color algorithm
const chalk = require('chalk');
const COLOR_CORRECT_SPOT = 'green';
const COLOR_WRONG_SPOT = 'yellow';
const COLOR_NOT_ANY_SPOT = 'gray';
// From https://codereview.stackexchange.com/a/274334
function guessColor(word, guess, index) {
// correct (matched) index letter
if (guess[index] === word[index]) {
return COLOR_CORRECT_SPOT;
}
let wrongWord = (wrongGuess = 0);
for (let i = 0; i < word.length; i++) {
// count the wrong (unmatched) letters
if (word[i] === guess[index] && guess[i] !== guess[index]) {
wrongWord++;
}
if (i <= index) {
if (guess[i] === guess[index] && word[i] !== guess[index]) {
wrongGuess++;
}
}
// an unmatched guess letter is wrong if it pairs with
// an unmatched word letter
if (i >= index) {
if (wrongGuess === 0) {
break;
}
if (wrongGuess <= wrongWord) {
return COLOR_WRONG_SPOT;
}
}
}
// otherwise not any
return COLOR_NOT_ANY_SPOT;
}
// printGuess('hello', 'halo')
const printGuess = (word, guess) => {
let msg = '';
for (let i = 0; i < word.length; i++) {
const color = guessColor(word, guess, i);
const letter = guess.charAt(i);
msg += chalk[color](letter);
}
console.log(msg);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment