Skip to content

Commit ed85cf8

Browse files
authored
Create 843-guess-the-word.js
1 parent 9cbc46f commit ed85cf8

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

843-guess-the-word.js

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* // This is the master's API interface.
3+
* // You should not implement it, or speculate about its implementation
4+
* function Master() {
5+
*
6+
* @param {string[]} wordlist
7+
* @param {Master} master
8+
* @return {integer}
9+
* this.guess = function(word) {
10+
* ...
11+
* };
12+
* };
13+
*/
14+
/**
15+
* @param {string[]} wordlist
16+
* @param {Master} master
17+
* @return {void}
18+
*/
19+
const findSecretWord = function (wordlist, master) {
20+
let group = wordlist
21+
for (let i = 0; i < 10; i++) {
22+
let currentGuess = findTheTypical(group)
23+
let res = master.guess(currentGuess)
24+
if (res === 6) return
25+
let tmp = []
26+
for (let j = 0; j < group.length; j++) {
27+
if (diff(group[j], currentGuess) === 6 - res) tmp.push(group[j])
28+
}
29+
group = tmp
30+
}
31+
}
32+
function findTheTypical(wordlist) {
33+
const count = Array.from({ length: 6 }, (x) => new Object())
34+
for (let i = 0; i < wordlist.length; i++) {
35+
for (let j = 0; j < 6; j++) {
36+
const cur = wordlist[i][j]
37+
if (count[j][cur] === undefined) count[j][cur] = 1
38+
else count[j][cur]++
39+
}
40+
}
41+
let maxPos = 0,
42+
maxCount = 0,
43+
maxAlp = ''
44+
for (let i = 0; i < 6; i++) {
45+
for (let k of Object.keys(count[i])) {
46+
if (count[i][k] > maxCount) {
47+
maxCount = count[i][k]
48+
maxPos = i
49+
maxAlp = k
50+
}
51+
}
52+
}
53+
for (let i = 0; i < wordlist.length; i++) {
54+
if (wordlist[i][maxPos] === maxAlp) return wordlist[i]
55+
}
56+
}
57+
function diff(a, b) {
58+
let count = 0
59+
for (let i = 0; i < a.length; i++) {
60+
if (a[i] !== b[i]) count++
61+
}
62+
return count
63+
}

0 commit comments

Comments
 (0)