Skip to content

Instantly share code, notes, and snippets.

@barrettclark
Last active August 29, 2015 14:08
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 barrettclark/a68bb17c618abcf4ea8e to your computer and use it in GitHub Desktop.
Save barrettclark/a68bb17c618abcf4ea8e to your computer and use it in GitHub Desktop.
Whirly Word Solver
class WordList
attr_reader :words
def initialize
@words = Array.new
read_list
end
def check_letters(*letters)
letter_counts = letters.each_with_object(Hash.new(0)) { |letter, counts| counts[letter] += 1 }
@words.select do |word|
word_counts = word.chars.each_with_object(Hash.new(0)) { |letter, counts| counts[letter] += 1 }
word_counts.keys.all? { |letter| letters.include?(letter) && word_counts[letter] <= letter_counts[letter] } &&
word.length >= 3 &&
word.length <= letters.count
end.sort_by { |word| [word.length, word] }
end
private
def read_list
IO.foreach('wordsEn.txt') { |line| @words << line.chomp }
puts "#{@words.count} words read into memory"
end
end
__END__
NOTE: Set logic is fun. This isn't the best answer, but I liked the proper_superset method
http://www.ruby-doc.org/stdlib-2.1.4/libdoc/set/rdoc/Set.html#method-i-3E
def check_letters(*letters)
require 'set'
letter_set = letters.to_set
@words.select do |word|
letter_set > word.chars.to_set && word.length >= 3 && word.length <= letters.count
end.sort_by { |word| [word.length, word] }
end
Usage:
$ wget http://www-01.sil.org/linguistics/wordlists/english/wordlist/wordsEn.txt
$ irb -r ./words
>> wl = WordList.new; nil
109582 words read into memory
>> wl.check_letters('s', 'h', 'c', 'p', 't', 'u')
=> ["cps", "cpu", "csp", "cst", "cts", "cup", "cut", "hts", "hup", "hut", "pct", "pts", "pus", "put", "sup", "tsp", "tup", "uhs", "ups", "cups", "cusp", "cuts", "huts", "push", "puts", "scut", "shut", "such", "supt", "thus", "tups", "tush", "putsch"]
@barrettclark
Copy link
Author

This isn't meant to be the world's best solver. I was just stuck on a word ("putsch") and wanted to try to solve it with code. Typically I don't like to change/create data in initialization. This was just for funsies.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment