Skip to content

Instantly share code, notes, and snippets.

@daveyeu
Created July 18, 2009 05:13
Show Gist options
  • Save daveyeu/149419 to your computer and use it in GitHub Desktop.
Save daveyeu/149419 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require "pp"
DICTIONARY_PATH = "/usr/share/dict/words"
if ARGV.empty?
puts "Usage: ruby t9-lookup.rb 12345 [max_length]"
exit 1
end
# Build the dictionary
dictionary = {}
File.open(DICTIONARY_PATH, "r") do |file|
file.each do |line|
word = line.strip
t9 = word.tr("a-z", "22233344455566677778889999")
dictionary[t9] ||= []
dictionary[t9] << word
end
end
# Lookup t9 and print matching words
t9 = ARGV[0]
if max_length = ARGV[1]
matching_t9s = dictionary.keys.select { |k| k.start_with?(t9) && k.size <= max_length.to_i }
matching_words = matching_t9s.map { |t9| dictionary[t9] }.flatten.sort_by { |t9| -t9.size }
pp matching_words
else
pp dictionary[t9]
end
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment