Skip to content

Instantly share code, notes, and snippets.

@imphasing
Created November 1, 2012 20:14
Show Gist options
  • Save imphasing/3996182 to your computer and use it in GitHub Desktop.
Save imphasing/3996182 to your computer and use it in GitHub Desktop.
# Markov chain text generator.
# This is a test comment.
start_text = File.read(ARGV[0])
text_chars = start_text.split(//)
stats = {}
text_chars.each_with_index do |letter, index|
current_pair = [letter, text_chars[index+1], text_chars[index+2]].join
if text_chars[index+3] != nil
stats[current_pair] = {} if stats[current_pair] == nil
if stats[current_pair][text_chars[index+3]] == nil
stats[current_pair][text_chars[index+3]] = 1
else
stats[current_pair][text_chars[index+3]] += 1
end
end
end
puts stats.inspect
def write_char(stats, previous)
puts "previous: #{previous}"
keys = stats[previous].keys
keys[rand(keys.length)]
end
def make_string(stats, len)
pairs = stats.keys
start_pair = pairs[rand(pairs.length)]
generated = start_pair.dup
len.times do |i|
previous = generated
generated << write_char(stats, generated[-1].chr + generated[-2].chr + generated[-3].chr)
end
generated
end
puts make_string(stats, 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment