-
Notifications
You must be signed in to change notification settings - Fork 0
/
suggest-word.mjs
74 lines (59 loc) · 1.41 KB
/
suggest-word.mjs
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { createRequire } from "module";
// @ts-ignore
const require = createRequire(import.meta.url);
const words = require("./words.json");
/**
* @typedef {Map<string,number[]>} LetterPositions
*/
/**
*
* @param {string[]} absent
* @param {LetterPositions} correct
* @param {LetterPositions} present
* @param {string[]} bannedWords
*/
export function suggestWord(absent, correct, present, bannedWords) {
const wordLength = 5;
const suggestions = words.filter((word) => {
if (word.length !== wordLength) {
return false;
}
if (bannedWords.includes(word)) {
return false;
}
for (const [letter, positions] of correct.entries()) {
if (positions.some((pos) => word[pos] != letter)) {
return false;
}
}
if (absent.some((letter) => word.includes(letter))) {
return false;
}
for (const [letter, exceptInPositions] of present.entries()) {
const indexes = getAllIndexes(word, letter);
if (!indexes.length) {
return false;
}
if (indexes.some((pos) => exceptInPositions.includes(pos))) {
return false;
}
}
return true;
});
return suggestions[0];
}
/**
*
* @param {string} word
* @param {string} val
* @returns
*/
function getAllIndexes(word, val) {
const indexes = [];
for (let i = 0; i < word.length; i++) {
if (word[i] === val) {
indexes.push(i);
}
}
return indexes;
}