[SOLUTION] Markov Chain (#74)

S

semmons99

# 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
@hadp, @notp = 0, 0
end

def read( book = @book )
prev = [ '', '' ]
words = File.open( book ).read.split
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 ] )
mChain.read
print mChain.get_chain.join( ' ' ), "\n"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top