Skip to content

Instantly share code, notes, and snippets.

Created Jan 15, 2012
Embed
What would you like to do?
Solution to Greed Ruby Koan
class Array
def occurrences_of(match)
if match.respond_to? :map
return match.map { |item| self.occurrences_of(item) }
else
return self.select{ |number| match == number }.size
end
end
end
def score rolls
result = 0
rules = [:single_double_rule, :triple_quadruple_quintuple_sextuple_rule, :three_pairs_rule, :straight_rule]
rules.each do |rule|
rule_result, is_final_result = method(rule).call rolls
return rule_result if is_final_result
result += rule_result
end
return result
end
def single_double_rule rolls
{ 1 => 100, 5 => 50 }.reduce(0) do |result, (dice_roll_result, points)|
result += points * rolls.occurrences_of(dice_roll_result).modulo(6).modulo(5).modulo(4).modulo(3)
end
end
def triple_quadruple_quintuple_sextuple_rule rolls
hat_trick_points = { 1 => 1000, 2 => 200, 3 => 300, 4 => 400, 5 => 500, 6 => 600 }
hat_trick_points.reduce(0) do |result, (dice_roll_result, points)|
occurrences = rolls.occurrences_of(dice_roll_result)
result = result +
points * occurrences.div(3) +
points * occurrences.div(4) +
points * occurrences.div(5) * 2 +
points * occurrences.div(6) * 3
end
end
def three_pairs_rule rolls
return 800, true if rolls.occurrences_of(1..6).select { |occurrence| occurrence == 2 }.length == 3
return 0
end
def straight_rule rolls
return 1200, true if rolls.occurrences_of(1..6).select { |occurrence| occurrence == 1 }.length == 6
return 0
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment