|
| 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