-
Notifications
You must be signed in to change notification settings - Fork 0
/
solve.js
114 lines (94 loc) · 2.91 KB
/
solve.js
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
const getLetterFrequencies = require("./helpers/getLetterFrequencies");
const calculateWordScores = require("./helpers/calculateWordScores");
const sortKeysByValue = require("./helpers/sortKeysByValue");
const { Form } = require("enquirer");
let words = require("./dict.json");
const chalk = require("chalk");
// Wrap the code in an async function, so that we can make use of the `await` keyword
async function solve() {
console.log(); // Just make some whitespace separation
const correctFeedback = new Set(["Y", "N", "W"]);
while (words.length > 0) {
const frequencies = getLetterFrequencies(words);
const wordScores = calculateWordScores(words, frequencies);
const wordsSortedByValue = sortKeysByValue(wordScores);
const bestWord = wordsSortedByValue[0];
console.log(
chalk.green("Try the following word: "),
chalk.bgGrey(bestWord)
);
const prompt = new Form({
name: "letters",
message:
"For each of the letters, enter Y (correct), N (incorrect), or W (wrong place). Use arrow keys for navigation. Press enter to submit",
choices: [...bestWord].map((letter, index) => ({
// Add 1 because it can't handle the name '0' for some reason
name: index + 1,
message: letter,
})),
});
const feedback = Object.values(await prompt.run()).map((val) =>
val.toUpperCase()
);
const feedbackValid = feedback.every((val) => correctFeedback.has(val));
if (feedback.every((a) => a === "Y")) {
console.log(chalk.green("Congrats!!!!"));
}
if (!feedbackValid) {
console.log(
"\n",
chalk.red(
"----- The provided input was not valid. Prompting again. -----"
),
"\n"
);
} else {
const excluded = new Set();
const included = [];
const final = [];
feedback.forEach((a, index) => {
const letter = bestWord[index];
if (a === "Y") {
final.push({
letter,
index,
});
}
if (a === "N") {
excluded.add(letter);
}
if (a === "W") {
included.push({
letter,
incorrectIndex: index,
});
}
});
words = words.filter((word) => {
for (let i = 0; i < word.length; i++) {
if (excluded.has(word[i])) {
return false;
}
}
for (let i = 0; i < included.length; i++) {
const row = included[i];
if (
!word.includes(row.letter) ||
word[row.incorrectIndex] === row.letter
) {
return false;
}
}
return final.every((row) => word[row.index] === row.letter);
});
}
}
if (!words.length) {
console.log(
chalk.red(
"There aren't any words left in the dictionary. Make sure you didn't make a mistake entering the data."
)
);
}
}
solve();