Velocity Reviews - Computer Hardware Reviews

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

Reply
Thread Tools

[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
@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"

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Optimizing large-scale Markov chain handler Oblomov Ruby 6 08-01-2007 11:20 PM
[SOLUTION] (#74) Markov Chain vsv Ruby 1 04-11-2006 01:05 PM
Re: Markov process representation kpp9c Python 8 03-16-2006 08:17 AM
markov query kpp9c Python 5 03-15-2006 01:12 AM
Markov chain with extras? temp@mclift.fsnet.co.uk Python 7 05-19-2005 06:23 PM



Advertisments