Skip to content

Commit 56bed79

Browse files
author
hieu
committed
Solve Problem 843 - Guess the word
1 parent ad030d8 commit 56bed79

File tree

2 files changed

+62
-1
lines changed

2 files changed

+62
-1
lines changed

src/contest/ReadMe.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ public class ReadMe {
2121
// heap: 1054[!] 882[!] 864[x]
2222
// design: 1352[x] 1348[x] 705[v]
2323
// bit manipulation: 1356[v] 1342[v] 1318[v]
24-
// other: 913[x] 1288[v] 843
24+
// other: 913[x] 1288[v] 843[x!]
2525

2626

2727
// x: not done or give up

src/others/Problem843_GuessWord.java

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package others;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
public class Problem843_GuessWord {
7+
8+
interface Master {
9+
int guess(String word);
10+
}
11+
12+
public void findSecretWord(String[] wordList, Master master) {
13+
// most overlapped word
14+
// guess --> matches
15+
// find all with matches
16+
17+
while (true) {
18+
String guess = mostOverlappedWord(wordList);
19+
int matches = master.guess(guess);
20+
if (matches == 6) return;
21+
List<String> wordList2 = find(wordList, guess, matches);
22+
wordList = wordList2.toArray(new String[0]);
23+
}
24+
}
25+
26+
private String mostOverlappedWord(String[] wordList) {
27+
int count[][] = new int[6][26], max = 0;
28+
for (String w : wordList) {
29+
for (int i = 0; i < w.length(); i++) {
30+
count[i][w.charAt(i) - 'a']++;
31+
}
32+
}
33+
String res = "";
34+
for (String w : wordList) {
35+
int score = 0;
36+
for (int i = 0; i < w.length(); i++) {
37+
score += count[i][w.charAt(i)-'a'];
38+
}
39+
if (score > max) {
40+
max = score;
41+
res = w;
42+
}
43+
}
44+
return res;
45+
}
46+
47+
private List<String> find(String[] wordList, String word, int k) {
48+
List<String> res = new ArrayList<>();
49+
for (String w : wordList) {
50+
if (match(word, w) == k) res.add(w);
51+
}
52+
return res;
53+
}
54+
55+
private int match(String w1, String w2) {
56+
int res = 0;
57+
for (int i = 0; i < w1.length(); i++)
58+
if (w1.charAt(i) == w2.charAt(i)) res++;
59+
return res;
60+
}
61+
}

0 commit comments

Comments
 (0)