[SOLUTION] Markov Chain (#74)

Discussion in 'Ruby' started by semmons99@gmail.com, Apr 9, 2006.

  1. Guest

    # 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"
     
    , Apr 9, 2006
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    7
    Views:
    547
  2. kpp9c

    markov query

    kpp9c, Mar 14, 2006, in forum: Python
    Replies:
    5
    Views:
    493
    Robert Kern
    Mar 15, 2006
  3. kpp9c
    Replies:
    8
    Views:
    308
    Max M
    Mar 16, 2006
  4. vsv
    Replies:
    1
    Views:
    115
    Dave Burt
    Apr 11, 2006
  5. Oblomov
    Replies:
    6
    Views:
    134
    Axel Etzold
    Aug 2, 2007
Loading...

Share This Page