Skip to content

Instantly share code, notes, and snippets.

@mchail
Created March 23, 2015 03:33
Show Gist options
  • Save mchail/d642c2a8e58c1875088e to your computer and use it in GitHub Desktop.
Save mchail/d642c2a8e58c1875088e to your computer and use it in GitHub Desktop.
Pirate Scrabble word finder
#!/usr/bin/env ruby
#
# Usage: ruby [filename] [word]
# Will return a list of up to ten words from the system dictionary
# that could be played before the provided word. It is up to the user
# to manually filter for "root" constraints.
# e.g.
# ruby pirates.rb marquisotte
class Yarr
def initialize(word)
@word = word.downcase
@sorted_word = sorted_word(@word)
end
def ideas
candidates = filter_dictionary
candidates[0...10]
end
def filter_dictionary
candidates = []
File.open('/usr/share/dict/words').each_line do |line|
candidate = line.strip.downcase
if valid_word?(candidate)
candidates << Candidate.new(candidate, @word)
end
end
candidates.sort_by!(&:size).reverse!
candidates
end
def valid_word?(candidate)
sorted_candidate = sorted_word(candidate)
regex = Regexp.new(sorted_candidate.split('').join('.*'))
# test that @word contains all candidate letters, but not in the candidate's exact order
!@sorted_word[regex].nil? && @word[candidate].nil?
end
def sorted_word(word)
word.split('').sort.join
end
end
class Candidate
def initialize(word, target)
@word = word
@target = target
end
def needs
target_letters = @target.split('')
@word.each_char do |char|
index = target_letters.find_index(char)
unless index.nil?
target_letters.delete_at(index)
end
end
target_letters.sort
end
def to_s
"#{@word} needs #{needs.join(', ')}"
end
def size
@word.size
end
end
puts Yarr.new(ARGV[0]).ideas
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment