Skip to content

Instantly share code, notes, and snippets.

@ansonhoyt
Created March 27, 2013 12:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ansonhoyt/5253841 to your computer and use it in GitHub Desktop.
Save ansonhoyt/5253841 to your computer and use it in GitHub Desktop.
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