One of my first ruby programs… unit tests available to anyone who cares!
class Prefix
attr_accessor :words
def initialize words
@words = words
end
def push word
shifted = @words.clone
shifted.shift
shifted << word
Prefix.new shifted
end
def [] index
@words[ index ]
end
def == prefix
return @words == prefix.words
end
def eql? other
return self == other
end
def hash
return @words.hash
end
end
class Suffix
def initialize
@words = Hash.new 0
end
def add word
@words[ word ] += 1
end
def frequency word
@words[ word ]
end
def next_word
wordlist = [ ]
@words.each { |word,freq|
freq.times{ wordlist << word }
}
index = rand wordlist.size
return wordlist[ index ]
end
end
class Markov
def initialize data , prefix = (Prefix.new [nil,nil])
@suffixes = Hash.new
data.each_line { |line|
line.split( / / ).each{ |word|
suffix = @suffixes[ prefix ]
if nil == suffix
suffix = Suffix.new
@suffixes[ prefix ] = suffix
end
suffix.add word
prefix = prefix.push word
}
}
end
def suffixes prefix
@suffixes[ prefix ]
end
def chain prefix = (Prefix.new [nil,nil])
while nil != ( suff = suffixes prefix )
word = suff.next_word
print " #{word}"
prefix = prefix.push word
end
end
end
if nil != ARGV[0]
( Markov.new ARGF.read ).chain
else
puts <<END
Usage : markov.rb
END
end
···
-----Original Message-----
From: Lyle Johnson [mailto:lyle@users.sourceforge.net]
Sent: 26 February 2003 15:36
To: ruby-talk@ruby-lang.org
Subject: Re: Matrix op speaks. Computer programmers needed to
build matrix.Matrix Four wrote:
It is certainly to your benefit to free the time needed to
read this
article entirely. Please post it to as many newsgroups as you can.OK, overwhelming curiosity compelled me to go their website
(http://matrixfour.com). Matrix Four Ltd. appears to be a legitimate
business, a graphic design studio. Perhaps the sender address
was spoofed.What I was really wondering was if anyone tell if this was
generated by
one of those programs (sorta like chat-bots) that can analyze
texts and
then generate random text that mimics the style of the
original? Or did
some deranged person really came up with all of this on his own?