I have attained enlightenment
As part of my Ruby learning process I started the Ruby Koans tutorial, and today I finally completed it. It only took me a couple of hours (spread over a few days) and it was really fun. Koans 177 through 184 were my favorite, they are about a “scoring project” described this way:
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.
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
The problem is really simple, but I did my best to solve it in the most “Rubyish” way possible. The final version of my implementation is this:
def score(dice)
rank = Hash. new( 0)
dice. each { | x| rank[x] += 1 }
finalScore = (rank[ 1] / 3) * 1000
finalScore += 100 * (rank[1] % 3)
finalScore += 50 * (rank[5] % 3)
rank. delete(1)
rank. keys. select{|key| rank[key] > 2}. each do |x|
finalScore += x * 100
end
finalScore
end
I think I could have made it smaller, but at the expense of readability. Any comments from the more seasoned Ruby developers out there?