Skip to content

Instantly share code, notes, and snippets.

Created January 15, 2012 21:51
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 anonymous/1617603 to your computer and use it in GitHub Desktop.
Save anonymous/1617603 to your computer and use it in GitHub Desktop.
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