ruby/words.rb: find all words an array of letters can make
This commit is contained in:
parent
9e16541e36
commit
92515ff218
|
@ -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
|
Loading…
Reference in New Issue