Skip to content

Instantly share code, notes, and snippets.

@EvilScott
Created January 12, 2015 20:39
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 EvilScott/cb517867cff52cf95465 to your computer and use it in GitHub Desktop.
Save EvilScott/cb517867cff52cf95465 to your computer and use it in GitHub Desktop.
Word generation using markov chains
prefix = (ARGV[0] || 2).to_i
words = (ARGV[1] || 5).to_i
corpus = `cat /usr/share/dict/words`.downcase
dict = Hash.new { |h,k| h[k] = [] }
corpus.split("\n").each do |word|
chars = "#{word} ".chars.to_a
until chars.length < (prefix + 1) do
dict[chars.first(prefix).join] << chars[prefix]
chars.shift
end
end
sentence = []
words.times do
word = ''
loop do
word += dict.keys.sample if word.empty?
word += dict[word.chars.to_a.last(prefix).join].sample
break if word.chars.to_a.last == ' '
end
sentence << word
end
puts sentence.join
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment