From: Barry Dmytro Date: 2006-04-10T09:17:33+09:00 Subject: Re: [QUIZ][SOLUTION] Markov Chains (#74) --pf9I7BMVVzbSWLtt Content-Type: text/plain; charset=us-ascii Content-Disposition: inline My approach isn't terribly complex, but it was fun to write. It requires that you have a plain text file "book.txt" in the directory of execution. I used http://www.gutenberg.org/dirs/etext91/alice30.txt for all of my tests and my favorite phrase that it came up with was: Beautiful soup beauootiful soooop soooop of evidence said the queen turning to the dormouse. How is works is loads each word into a hash stripping punctuation and capitalization associating each word with an array of common words that it is followed by. One word is picked by random to start us off then it picks randomly commonly chained words from there till it ends up with a word that was at the end of sentence in the original document. Kind Regards, -------------------------------------------------------------------- Barry Dmytro badcherry@mailc.net http://badcherry.org/ -------------------------------------------------------------------- --pf9I7BMVVzbSWLtt Content-Type: text/plain; charset=us-ascii Content-Disposition: attachment; filename="74.rb" #!/usr/bin/env ruby class Array def rand self[Kernel::rand(self.size-1)] end end words = {} File::open("book.txt") do |f| book = f.read.gsub(/\n/,"") arr = book.split arr.each_with_index do |word,index| eos = false eos = true if word[word.size-1].chr == "." word = word.gsub(/\W/,"").downcase words[word] = [] unless words.has_key? word if eos == true then words[word] << :EOS elsif arr.size-1 != index then next_word = arr[index+1] next_word = next_word.gsub(/\W/,"").downcase words[word] << next_word else words[word] << :EOS end end end word = words.keys.rand state = word.capitalize while true word = words[word].rand break if word == :EOS state << " " << word end puts state + "." --pf9I7BMVVzbSWLtt--