Skip to content

Instantly share code, notes, and snippets.

@sunny
Created May 7, 2015 13:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunny/3397136edd65c0d4695f to your computer and use it in GitHub Desktop.
Save sunny/3397136edd65c0d4695f to your computer and use it in GitHub Desktop.
Markov
# Get phrases
phrases = File.readlines('phrases.txt')
.map { |p| p.gsub(/["()*]/, '') }
.map { |p| p.gsub(/ +/, ' ').strip }
.reject { |p| p.split(' ').size < 2 }
.uniq
# Get first words
starters = phrases.map { |p| p.split(' ').first }
# Create a chain { key => [word1, word2] }
chain = {}
phrases.each do |phrase|
words = phrase.split(' ')
words.each_with_index do |word, index|
next_word = words[index + 1]
chain[word] ||= []
chain[word] << next_word
end
end
10.times do
phrase = []
# first word from starters
word = starters.sample
while word
phrase << word
# next word from the chain
word = chain[word].sample
end
phrase = phrase.join(' ')
puts phrase unless phrases.include?(phrase)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment