Markov Chains and Hamlet

Lately I've been feeling adventurous and that got me thinking programming-wise. Is it possible to write a play like Hamlet by using Markov Chains?

Yes! There's a cheating way of doing that by using Markov Chain text generator.

It works more or less like this:

1. Take some text as input (e.g., the complete works of Shakespeare).

2. For every distinct word in it, determine what words follow it, and with what frequency.

3. Pick a word to start with -- e.g., choose one at random from all the words that start sentences.

4. Randomly choose a word to follow it, using the frequencies found in step 2.



If you're not afraid of a little bit of computer algorithmy, read on. This is the answer you've all been waiting for concerning Shakespeare's works.