Generating Text

You will make use of another method that has been provided: sampleWord. This method takes a ChainingHashMap (counts) and a number (totalCount). The map is assumed to map words to counts. The number totalCount should be the total count of all the words in the map. The sampleWord method randomly selects a word based on the relative frequency of the words in counts and returns it. This method makes use of your iterator, so it had better work right!

Your generateText method should:

  • Generate the first word using the frequencies in the totalTable (pass totalTable and

totalWords to sampleWord) and add it to the text.

  • In a loop, until you’ve generated the specified number of words:
    • Generate and add the next word using the frequencies in countTable associated with the last word (pass the map in countTable associated with the last word as well as the count in totalTable associated with the last word).
  • Return the text with “…” added to the beginning and end.

For instance, if you trained your TextGenerator on ‘a b a b a’ then generateText(4) should return ‘…a b a b…’ around half the time and ‘…b a b a…’ the other half.

You have been provided a main function that takes a filename as a command line parameter. The file should contain the source text. The program creates a TextGenerator, opens the given file, trains the TextGenerator using the contents of the file, uses the TextGenerator to generate 100 words, and prints the generated text.