ruby/words.rb: find all words an array of letters can make

This commit is contained in:
Nick Chambers 2021-07-25 20:33:06 -05:00
parent 9e16541e36
commit 92515ff218
1 changed files with 32 additions and 0 deletions

32
ruby/words.rb Normal file
View File

@ -0,0 +1,32 @@
#!/usr/bin/env ruby
WORDS = File.open("/usr/share/dict/words", &:read).lines.map do |word|
word.strip.downcase
end.freeze
def word?(word)
WORDS.include? word.downcase
end
def permute(letters, prefix: "", &cb)
1.upto letters.size do
cur_prefix = prefix + letters.first
test_set = letters[1..]
if letters.size > 2
permute test_set, prefix: cur_prefix, &cb
else
word = cur_prefix + test_set.join
if word? word
yield word
end
end
letters = letters.rotate
end
end
permute %w[u h s e t l] do |word|
puts word
end