Created
January 12, 2015 20:39
-
-
Save EvilScott/cb517867cff52cf95465 to your computer and use it in GitHub Desktop.
Word generation using markov chains
This file contains 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
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