Skip to content

Instantly share code, notes, and snippets.

@allcentury
Created December 16, 2015 15:04
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 allcentury/43fd7e85129041f6495f to your computer and use it in GitHub Desktop.
Save allcentury/43fd7e85129041f6495f to your computer and use it in GitHub Desktop.
scrabble score
require 'set'
class Scrabble
class Letter
attr_reader :point_value
def initialize(input)
@input = input
@point_value = find_value
end
private
attr_reader :input
LETTER_VALUES = {
1 => Set.new(["a", "e", "i", "o", "u", "l", "n", "r", "s", "t"]),
2 => Set.new(["d", "g"]),
3 => Set.new(["b", "c", "m", "p"]),
4 => Set.new(["f", "h", "v", "w", "y"]),
5 => Set.new(["k"]),
8 => Set.new(["j", "x"]),
10 => Set.new(["q", "z"])
}.freeze
# runtime here is not much of a concern and using #find with a Set should be fine for
# 99.9% of words
def find_value
LETTER_VALUES.find { |_, letters| letters.include?(input.downcase) }.first
end
end
end
class Scrabble
class Bonus
attr_reader :multiplier_value
def initialize(bonus_type)
@bonus_type = bonus_type
@multiplier_value = find_value
end
private
attr_reader :bonus_type
BONUS_VALUES = {
single: 1,
double: 2,
triple: 3
}.freeze
def find_value
BONUS_VALUES[bonus_type]
end
end
end
class Scrabble
attr_reader :input, :bonus
def initialize(raw_word, bonus = :single)
@input = sanitize(raw_word)
@bonus = Bonus.new(bonus)
end
def score
return 0 if input.size == 0
letters = input.chars.map { |char| Letter.new(char) }
letters.map(&:point_value).reduce(:+) * bonus.multiplier_value
end
def self.score(input)
new(input).score
end
private
def sanitize(raw_word)
return "" unless raw_word
raw_word.gsub(/\t| |\n/, "")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment