DEV Community

Albert Martin
Albert Martin

Posted on

Scoring a Wordle Guess in JavaScript (and the Double-Letter Trap)

Wordle looks simple: green for the right letter in the right place, yellow for the right letter in the wrong place, grey otherwise. The interesting part is getting the colours right when a letter appears more than once. Here is a small, correct scoring function you can drop into your own clone.

The naive version (and why it is wrong)

The first idea most people try is: for each letter in the guess, green if it matches the answer at that index, yellow if the answer includes it anywhere, grey otherwise. That breaks with duplicates. If the answer is CRANE and you guess EERIE, the naive version marks several E tiles yellow even though the answer has only one E.

A two-pass solution

First mark all greens and count the remaining unmatched letters in the answer. Then do a second pass for yellows, using up those counts.

function scoreGuess(guess, answer) {
  const result = Array(5).fill('grey');
  const remaining = {};

  // Pass 1: greens, and count leftover answer letters
  for (let i = 0; i < 5; i++) {
    if (guess[i] === answer[i]) {
      result[i] = 'green';
    } else {
      remaining[answer[i]] = (remaining[answer[i]] || 0) + 1;
    }
  }

  // Pass 2: yellows, consuming leftover counts
  for (let i = 0; i < 5; i++) {
    if (result[i] === 'green') continue;
    const ch = guess[i];
    if (remaining[ch] > 0) {
      result[i] = 'yellow';
      remaining[ch]--;
    }
  }
  return result;
}

console.log(scoreGuess('EERIE', 'CRANE'));
// ['grey','grey','yellow','grey','green']
Enter fullscreen mode Exit fullscreen mode

Unlimited mode

The daily game picks one answer per day from a date-based index. An unlimited version just picks a random answer from the word list each round and resets the board, so the scoring function above stays exactly the same.

If you want to compare your clone against a working version, Wordle Unlimited is a free browser game with the same rules and no daily limit, handy for testing edge cases like double letters.

Top comments (0)