Created
September 15, 2014 22:25
-
-
Save pchittum/33447549d9a425652f19 to your computer and use it in GitHub Desktop.
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
require 'getoptlong' | |
data_file = 'data.txt' | |
words_to_generate = 10 | |
min_length = 3 | |
max_length = 9 | |
opts = GetoptLong.new( | |
["--datafile", "-d", GetoptLong::OPTIONAL_ARGUMENT], | |
["--number-of-words", "-n", GetoptLong::OPTIONAL_ARGUMENT] | |
) | |
opts.each do |opt, arg| | |
case opt | |
when '--datafile' | |
data_file = arg | |
when '--number-of-words' | |
words_to_generate = arg.to_i | |
end | |
end | |
start_pairs = [] | |
follower_letters = Hash.new('') | |
# when done array start_pairs will have the first two chars of every input name | |
# follower_letters hash will have random keys with randomized string values | |
File.open(data_file, 'r') do |file| | |
#file->io->string->remove end char and line returne->to lower->turn all white space to ' ' | |
#seems to_a is superfluous to me as chars should return an array anyway??? | |
chars = file.read.chomp.downcase.gsub(/\s/, ' ').chars.to_a | |
#puts chars | |
# | |
chars.push(chars[0], chars[1]) | |
#puts chars | |
(chars.length-2).times do |i| | |
if chars[i] =~ /\s/ #if I find whitespace | |
start_pairs.push(chars[i+1, 2].join) #take the next two charaters concat and stuff into array | |
end | |
#create a bunch of random keys add them | |
follower_letters[chars[i, 2].join]=follower_letters[chars[i,2].join]+chars[i+2,1].join | |
end | |
#puts start_pairs | |
puts follower_letters | |
end | |
def generate_word(word, follower_letters, min_length) | |
last_pair = word[-2, 2] #get the last 2 chars of "word" which is a passed in start_pair element | |
#doesn't matter first call, but on recursive calls, this grabs a new key | |
letter = follower_letters[last_pair].slice(rand(follower_letters[last_pair].length), 1) | |
if word =~ /\s$/ | |
return word unless word.length <= min_length | |
return generate_word(word[-1, 1]+letter, follower_letters, min_length) | |
else | |
word = word.gsub(/^\s/, '') | |
return generate_word(word+letter, follower_letters, min_length) | |
end | |
end | |
words_to_generate.times do |i| | |
puts generate_word(start_pairs[rand start_pairs.length], follower_letters, min_length)[0, max_length].capitalize | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment