Skip to content

Instantly share code, notes, and snippets.

@ansonhoyt ansonhoyt/puzzle.rb
Created Mar 27, 2013

Embed
What would you like to do?
Finds words of a given length that are made from the given letters. Helps solve puzzles in the "Four Pictures, One Word" game.
#!/usr/bin/envy ruby
#
# Finds words of a given length that are made from the given letters.
# Helps solve "Four Pictures, One Word" puzzles.
# @author Anson Hoyt
require 'optparse'
# Parse command line arguments
def parse(args)
options = {}
opts = OptionParser.new do |opts|
opts.banner = "Usage: #{$0} letters length"
opts.on(:REQUIRED, "--length LENGTH", "Length of the word") do |length|
options[:length] = length
end
opts.on(:REQUIRED, "-L", "--letters LETTERS", "Letters which spell the word") do |letters|
options[:letters] = letters
end
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
end
opts.parse!
abort opts.banner unless options[:letters] # Require file to be specified
options
end # parse()
options = parse(ARGV)
letters = options[:letters]
length = options[:length]
matches = []
words = (`cat /usr/share/dict/words`).split("\n")
words.grep(/^[#{letters}]{#{length}}$/).each {|word|
unmatched_letters = letters.clone
isMatch = true
word.chars.each {|letter|
i = unmatched_letters.index(letter)
if i
unmatched_letters[i] = ' '
else
# puts "#{word}: can't find '#{i}' in #{unmatched_letters}"
isMatch = false
end
}
matches << word if isMatch
}
puts "Looked through #{words.count} words to find every #{length}-letter word spelt with '#{letters}'"
matches.each_slice(4) {|a|
puts "#{a[0]}\t#{a[1]}\t#{a[2]}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.