Created
April 26, 2012 18:08
-
-
Save poemdexter/2501552 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Markov | |
def initialize | |
@firsts = [] | |
@data = {} | |
end | |
def add(statement) | |
words = statement.split | |
if words.length > 2 | |
@firsts << words[0] + " " + words[1] | |
for x in 0..(words.length - 2) | |
piece = words[x] + " " + words[x+1] | |
if @data.has_key?(piece) | |
if words[x+2] != nil | |
@data[piece] << words[x+2] | |
else | |
@data[piece] << "!!!END!!!" | |
end | |
else | |
if words[x+2] != nil | |
@data[piece] = [words[x+2]] | |
else | |
@data[piece] = ["!!!END!!!"] | |
end | |
end | |
end | |
end | |
end | |
def get_chain | |
fragment = @firsts[rand(@firsts.length - 1)] | |
statement = fragment | |
while (nextlist = @data[fragment]) != nil | |
nextword = nextlist[rand(nextlist.length - 1)] | |
if nextword == "!!!END!!!" | |
break | |
elsif statement.split.length > 20 | |
break | |
else | |
statement = statement + " " + nextword | |
fragment = fragment.split[1] + " " + nextword | |
end | |
end | |
statement | |
end | |
end | |
text1 = "hi my name is Al and i live in a box that i like very much and i can live in there as long as i want" | |
text2 = "i live in a cat and i can live in a litter box as long as my name is Daniel" | |
m = Markov.new | |
m.add(text1) | |
m.add(text2) | |
puts m.get_chain |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment