Skip to content

Instantly share code, notes, and snippets.

@kejadlen
Last active July 6, 2016 04:33
Show Gist options
  • Save kejadlen/fc9210576f166bec55d272cea70d7fcd to your computer and use it in GitHub Desktop.
Save kejadlen/fc9210576f166bec55d272cea70d7fcd to your computer and use it in GitHub Desktop.
module Scrabble
POINTS = {}
{
'EAIONRTLSU' => 1,
'DG' => 2,
'BCMP' => 3,
'FHVWY' => 4,
'K' => 5,
'JX' => 8,
'QZ' => 10,
}.each do |letters, points|
letters.downcase.chars.each do |letter|
POINTS[letter] = points
end
end
class Cheater
attr_reader *%i[ word_map ]
def initialize(words: [])
words ||= File.read('/usr/share/dict/words').downcase.split("\n")
@word_map = words.each
.with_object(Hash.new {|h,k| h[k] = Set.new }) {|word, map|
key = word.chars.sort.join
map[key] << word
blanks(word).flat_map {|w| blanks(w) }.each do |blank|
key = blank.chars.sort.join
map[key] << word
end
}
end
def possible_words(tiles, required: '')
tiles = tiles.downcase.chars
words = (2..tiles.length).flat_map {|n|
tiles.combination(n).flat_map {|combination|
word_map[(combination << required).sort.join].to_a
}
}
Hash[words.map {|word|
points = word.chars.map {|c| POINTS[c] }.reduce(:+)
[word, points]
}]
end
private
def blanks(word)
word.length.times.map { |i|
blank = word.chars
blank[i] = ??
blank.join
}
end
end
end
require 'minitest/autorun'
class TestCheater < Minitest::Test
include Scrabble
def setup
@cheater = Cheater.new(words: %w[ alice bob spot tops pasta ])
end
def test_word_map
assert_equal Set.new(%w[ pasta ]), @cheater.word_map['aapst']
assert_equal Set.new(%w[ alice ]), @cheater.word_map['aceil']
assert_equal Set.new(%w[ bob ]), @cheater.word_map['bbo']
assert_equal Set.new(%w[ spot tops ]), @cheater.word_map['opst']
assert_equal Set.new(%w[ pasta ]), @cheater.word_map['?aapt']
assert_equal Set.new(%w[ pasta ]), @cheater.word_map['??apt']
end
def test_possible_words
assert_equal({ 'spot' => 6, 'tops' => 6 }, @cheater.possible_words('pots'))
assert_equal({ 'spot' => 6, 'tops' => 6 }, @cheater.possible_words('potss'))
assert_equal({ 'pasta' => 7 }, @cheater.possible_words('potsa', required: 'a'))
end
def test_blanks
assert_equal({
'spot' => 6,
'tops' => 6,
'pasta' => 7,
}, @cheater.possible_words('pats?'))
end
end
@zenspider
Copy link

You own the input hash, so why do it in uppercase only to downcase it?

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