Question

I have a question on how I can approach a situation. I am still fairly new to coding. For my class our teacher is having us make the classic game of hangman, and I am stuck on a situation. I am just curious to see if anyone can help me get the logic down for this situation.

The problem I am having is this:

 The secret word is: hangman
 Your progress: -------
 Wrong guesses:
 Guesses remaining: 10
 Number of words possible: 7359
 Guess a letter: e

How would you go about finding the number of possible words remaining? We are given a dictionary that we read in and get the number of words from that. Can pretty much use anything to solve it. The problem is every time you guess a character correct the list will shrink like this:

 The secret word is: hangman
 Your progress: -an--an
 Wrong guesses: eix
 Guesses remaining: 7
 Number of words possible: 3
 Guess a letter: g

Just hope you guys can give me some ideas!

Thanks!

Was it helpful?

Solution

Let's say that your dictionary words are stored in a collection of some sort - say, a List<String>. Let's also assume that you know how to build a string that represents the current guessing state (i.e. "-an--an" from your example).

All you need to do is writing a function like this:

static boolean checkMatch(String candidateWord, String currentGuess) {
    return ...;
}

Your function needs to implement this logic:

  • If candidateWord and currentGuess have different lengths, return false. Otherwise,
  • Check each letter of the candidateWord against the letter of the currentGuess in the same position
  • If the letter of the currentGuess is a dash '-' or if it matches the letter of candidateWord in the same position, move on to the next letter
  • Otherwise, return false
  • Once you reach the end of the word, return true.

With this function in hand, you could take the current guess, check it against each dictionary word, and increment the count for each time the checkMatch returns true. This would give you the number of potential matches.

OTHER TIPS

A worst solution maybe using regex and go through each of the words after one valid guessing.

To make this a little bit better, maybe pruning a little using length() ...


Oh, keep a Set of current valid words. (so only shrinking the set instead of go through each word)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top