Skip to content

Instantly share code, notes, and snippets.

@mjansen401
Created March 2, 2011 02:41
Show Gist options
  • Save mjansen401/850372 to your computer and use it in GitHub Desktop.
Save mjansen401/850372 to your computer and use it in GitHub Desktop.
Greed koan refactored
class Greed
# Greed is a dice game where you roll up to five dice to accumulate
# points. The following "score" function will be used 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.
ONES_MULTIPLIER = 10
ROLLS_IN_A_SET = 3
SINGLES_MULTIPLIER = 10
SET_MULTIPLIER = 100
def score(dice)
@score = 0
dice_count = count_rolls(dice)
dice_count.each do |side, count|
if side == 1
@score += score_ones(side,count)
elsif side == 5
@score += score_fives(side,count)
elsif has_set?(count)
@score += score_sets(side)
end
end
return @score
end
def has_set?(count)
count >= ROLLS_IN_A_SET
end
def score_ones(side,count)
ONES_MULTIPLIER * score_special_side(side,count)
end
def score_fives(side,count)
score_special_side(side,count)
end
def score_special_side(side,count)
temp_score = 0
if has_set?(count)
temp_score += score_sets(side) + score_singles(side,count-ROLLS_IN_A_SET)
else
temp_score += score_singles(side,count)
end
return temp_score
end
def score_sets(side)
( SET_MULTIPLIER * side)
end
def score_singles(side,count)
(SINGLES_MULTIPLIER * side) * count
end
def count_rolls(dice)
rolls = Hash.new(0)
dice.each{|roll| rolls[roll] += 1}
return rolls
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment