Consider a guessing game in which a player tries to guess a hidden word. The hidden word contains only capital letters and has a length known to the player. A guess contains only capital letters and has the same length as the hidden word.
After a guess is made, the player is given a hint that is based on a comparison between the hidden word and the guess. Each position in the hint contains a character that corresponds to the letter in the same position in the guess. The following rules determine the characters that appear in the hint.
public class HiddenWord {
private String hiddenWord;
public HiddenWord(String hiddenWord) {
this.hiddenWord = hiddenWord;
}
public String getHint(String guess) {
StringBuilder hint = new StringBuilder();
for (int i = 0; i < hiddenWord.length(); i++) {
char guessChar = guess.charAt(i);
char hiddenChar = hiddenWord.charAt(i);
if (guessChar == hiddenChar) {
hint.append(hiddenChar); // Matching letter
} else if (hiddenWord.indexOf(guessChar) != -1) {
hint.append("+"); // Matching letter in a different position
} else {
hint.append("*"); // Not in the hidden word
}
}
return hint.toString();
}
public static void main(String[] args) {
HiddenWord puzzle = new HiddenWord("HARPS");
// Test cases
System.out.println("Guess: AAAAA, Hint: " + puzzle.getHint("AAAAA")); // plus A plus plus plus
System.out.println("Guess: HELLO, Hint: " + puzzle.getHint("HELLO")); // H****
System.out.println("Guess: HEART, Hint: " + puzzle.getHint("HEART")); // H**+*
System.out.println("Guess: HARMS, Hint: " + puzzle.getHint("HARMS")); // HAR*S
System.out.println("Guess: HARPS, Hint: " + puzzle.getHint("HARPS")); // HARPS
}
}
HiddenWord.main(null);
Guess: AAAAA, Hint: +A+++
Guess: HELLO, Hint: H****
Guess: HEART, Hint: H*++*
Guess: HARMS, Hint: HAR*S
Guess: HARPS, Hint: HARPS