Skip to content

Instantly share code, notes, and snippets.

@kevinpang
Created July 18, 2011 08:38
Show Gist options
  • Save kevinpang/1088913 to your computer and use it in GitHub Desktop.
Save kevinpang/1088913 to your computer and use it in GitHub Desktop.
Ruby Koans 2
# 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)
# Hash holds values seen in the roll and the number of duplicates for each
h = Hash.new(0)
dice.each { | d | h.store(d, h[d]+1) }
score = 0
score += h[1] * 100
score += 700 if h[1] >= 3 # 1000 bonus points, minus the 3 * 100 points for the 1's in the set
score += 200 if h[2] >= 3
score += 300 if h[3] >= 3
score += 400 if h[4] >= 3
score += h[5] * 50
score += 350 if h[5] >= 3 # 500 bonus points, minus the 3 * 50 points for the 5's in the set
score += 600 if h[6] >= 3
score
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment