843. Guess the Word
Explanation:
- We can solve this problem using the minimax algorithm combined with a heuristic function to minimize the number of incorrect guesses.
- The basic idea is to select a word from the list of words and use the feedback from the Master.guess() method to eliminate other words that do not match the feedback.
- We keep track of the count of exact matches between the guessed word and the secret word to guide our next guess.
- By selecting the next guess intelligently based on the feedback received, we can minimize the number of guesses required to find the secret word. :
import java.util.*;
class Solution {
public void findSecretWord(String[] wordlist, Master master) {
List<String> words = new ArrayList<>(Arrays.asList(wordlist));
for (int i = 0; i < 10; i++) {
String guess = getBestGuess(words);
int match = master.guess(guess);
if (match == 6) {
return;
}
words = filterWords(words, guess, match);
}
}
private String getBestGuess(List<String> words) {
return words.get((int) (Math.random() * words.size()));
}
private List<String> filterWords(List<String> words, String guess, int match) {
List<String> filtered = new ArrayList<>();
for (String word : words) {
if (countMatches(word, guess) == match) {
filtered.add(word);
}
}
return filtered;
}
private int countMatches(String word1, String word2) {
int count = 0;
for (int i = 0; i < word1.length(); i++) {
if (word1.charAt(i) == word2.charAt(i)) {
count++;
}
}
return count;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.