-
Notifications
You must be signed in to change notification settings - Fork 0
/
evaluate.ts
40 lines (35 loc) · 1.14 KB
/
evaluate.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { Accuracy } from "./components/Game";
export const evaluate = (
guessWord: string,
solutionWord: string
): Accuracy[] => {
// accuracies[i] corresponds to letter i
const accuracies: Accuracy[] = new Array(guessWord.length).fill("wrong");
// Need frequency map to handle letter duplicates in guess/solution word.
// e.g., with solutionWord "ae" and guessWord "ee", the boxes should be "grey, green".
const freqs: { [key: string]: number } = {};
for (const letter of solutionWord) {
if (!(letter in freqs)) {
freqs[letter] = 0;
}
freqs[letter]++;
}
// Mark the right letters in right pos.
for (let i = 0; i < guessWord.length; i++) {
if (guessWord[i] === solutionWord[i]) {
freqs[guessWord[i]]--;
accuracies[i] = "right";
}
}
// Mark the right letters in wrong pos.
for (let i = 0; i < guessWord.length; i++) {
if (
guessWord[i] !== solutionWord[i] && // Not in right pos...
freqs[guessWord[i]] > 0 // ...but occurs in the word w/o being all marked yellow or green...
) {
freqs[guessWord[i]]--;
accuracies[i] = "almost";
}
}
return accuracies;
};