Created
April 30, 2013 20:23
-
-
Save Jared-Prime/5491654 to your computer and use it in GitHub Desktop.
edit (4/30/2013 3:23pm) add a few comments
This file contains hidden or 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
class DictionaryKata < Array | |
# we cheat, knowing how many characters we have to match | |
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) | |
# this case statement only makes sense | |
# with the foreknowledge that "cat" has 3 letters | |
case step | |
when 0 | |
# preserve interior of the word | |
head = word[0] | |
tail = word[-1] | |
part = /^#{head}.#{tail}$/ | |
when 1 | |
# match the heads of the first result set | |
head = word[0..1] | |
part = /^#{head}/ | |
when 2 | |
# match the tails of the second result set | |
tail = word[-2..-1] | |
part = /#{tail}$/ | |
end | |
# return everything from the dictionary that matches | |
self.select { |word| word.match(part) } | |
end | |
end | |
# run a script for the results | |
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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment