Velocity Reviews > Ruby > [SOLUTION] Markov Chain (#74)

# [SOLUTION] Markov Chain (#74)

semmons99@gmail.com
Guest
Posts: n/a

 04-09-2006
# Shane Emmons
# Ruby Quiz #74 - Markov Chain
#
# Here is my solution. It is pretty simple. Mostly just
# a Ruby version of Mark V Shaney with a few modifications.
# so, take a look and let me know what you think. It would
# be pretty interesting to test this on source code and
# see if it could generate a working program. Have fun!

class MarkovChain

def initialize( book )
@book = book
@phrases = Hash.new
@phrase_breaks = Array.new
end

def read( book = @book )
prev = [ '', '' ]
words.each do |word|
word.gsub!( /["()\[\]]/, '' )
prev_two = prev.join( ' ' )
unless prev_two.eql?( ' ' )
@phrases[ prev_two ] = Array.new unless
@phrases.has_key?( prev_two )
@phrases[ prev_two ] << word.downcase
@phrase_breaks << prev_two if prev_two.match( /[.!?]\$/
)
end
prev.pop and prev.insert( 0, word )
end
end

def get_chain( num_want = 5 )
chain = Array.new
prev = [ '', '' ]
prev_two = prev.join( ' ' )
num_have = 0
while num_have < num_want
until @phrases.has_key?( prev_two )
prev_two = @phrase_breaks[ rand( @phrase_breaks.length
) ]
end
words = @phrases[ prev_two ]
word = words[ rand( words.length ) ]
chain << word
prev.shift and prev.push( word )
prev_two = prev.join( ' ' )
num_have += 1 if prev_two.match( /[.!?]\$/ )
end
chain
end

end

mChain = MarkovChain.new( ARGV[ 0 ] )
print mChain.get_chain.join( ' ' ), "\n"