public
Created

  • Download Gist
dictionary_kata.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
class DictionaryKata < Array
 
def initialize(word_size)
File.open("/usr/share/dict/words","r") do |words|
words.each do |word|
word.gsub!(/\n/,'')
self << word if word.size == word_size
end
end
end
 
def word_chain(word="cat", step=0)
case step
when 0
head = word[0]
tail = word[-1]
part = /^#{head}.#{tail}$/
when 1
head = word[0..1]
part = /^#{head}/
when 2
tail = word[-2..-1]
part = /#{tail}$/
end
 
self.select { |word| word.match(part) }
end
 
end
 
step = 0
node0 = "cat"
dictionary = DictionaryKata.new(3)
dictionary.word_chain(node0,step).each do |node1|
dictionary.word_chain(node1,step+1).each do |node2|
puts "%s => %s => %s => dog" % [node0, node1, node2] if dictionary.word_chain(node2,step+2).include?("dog")
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.