-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20.java
More file actions
72 lines (66 loc) · 2.12 KB
/
20.java
File metadata and controls
72 lines (66 loc) · 2.12 KB
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
// Q.20 Guess the Word
import java.util.ArrayList;
import java.util.List;
/**
* // This is the Master's API interface.
* // You should not implement it, or speculate about its implementation
* interface Master {
* public int guess(String word) {}
* }
*/
class Solution {
public void findSecretWord(String[] words, Master master) {
List<String> candidates = new ArrayList<>();
for (String word : words) {
candidates.add(word);
}
while (!candidates.isEmpty()) {
String guessWord = getBestGuess(candidates);
int matches = master.guess(guessWord);
if (matches == 6) {
return;
}
List<String> newCandidates = new ArrayList<>();
for (String word : candidates) {
if (countMatches(guessWord, word) == matches) {
newCandidates.add(word);
}
}
candidates = newCandidates;
}
}
private String getBestGuess(List<String> candidates) {
if (candidates.size() <= 2) {
return candidates.get(0);
}
int minMax = Integer.MAX_VALUE;
String bestGuess = candidates.get(0);
for (String candidate : candidates) {
int[] groups = new int[7];
for (String word : candidates) {
int matches = countMatches(candidate, word);
groups[matches]++;
}
int currentMax = 0;
for (int count : groups) {
if (count > currentMax) {
currentMax = count;
}
}
if (currentMax < minMax) {
minMax = currentMax;
bestGuess = candidate;
}
}
return bestGuess;
}
private int countMatches(String a, String b) {
int matches = 0;
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) == b.charAt(i)) {
matches++;
}
}
return matches;
}
}