Created
October 31, 2016 05:00
-
-
Save adamjgrant/0a33b88be33b8dc46da36037ba8580c9 to your computer and use it in GitHub Desktop.
Ruby Koans Dice Game
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Greed is a dice game where you roll up to five dice to accumulate | |
# points. The following "score" function will be used to calculate the | |
# score of a single roll of the dice. | |
# | |
# A greed roll is scored as follows: | |
# | |
# * A set of three ones is 1000 points | |
# | |
# * A set of three numbers (other than ones) is worth 100 times the | |
# number. (e.g. three fives is 500 points). | |
# | |
# * A one (that is not part of a set of three) is worth 100 points. | |
# | |
# * A five (that is not part of a set of three) is worth 50 points. | |
# | |
# * Everything else is worth 0 points. | |
# | |
# | |
# Examples: | |
# | |
# score([1,1,1,5,1]) => 1150 points | |
# score([2,3,4,6,2]) => 0 points | |
# score([3,4,5,3,3]) => 350 points | |
# score([1,5,1,2,4]) => 250 points | |
# | |
# More scoring examples are given in the tests below: | |
# | |
# Your goal is to write the score method. | |
def score(dice) | |
score = 0 | |
counts = Hash.new { |h, k| h[k] = 0 } | |
dice.each { |num| counts[num] += 1 } | |
# Reward 1000 if 3 1s | |
score += 1000 and counts[1] -= 3 if counts[1] >= 3 | |
# Reward 100x if x is found >= 3 times | |
counts.each do |number, count| | |
score += 100 * number and counts[number] -= 3 if count >= 3 | |
end | |
score += (counts[1] * 100) + (counts[5] * 50) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment