Skip to content

Instantly share code, notes, and snippets.

@dbrady
Created April 13, 2011 23:36
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 dbrady/918662 to your computer and use it in GitHub Desktop.
Save dbrady/918662 to your computer and use it in GitHub Desktop.
Dice Scoring in a single expression
def score(dice)
(1..6).map {|i| (dice.count(i)/3) * i * 100 }.inject {|a,b| a+b} + (dice.count(1)/3) * 900 + (dice.count(1)%3)*100 + (dice.count(5)%3)*50
end
# Wait, what? Back that shit up a minute.
#
# Reconsider the rules of Greed as follows:
# 1. Score each triple of value k as k*100. This gives a correct score for all triples EXCEPT 1's--we're 900 points short.
# 2. Add in a 900-point bonus for each triple of 1's
# 3. Add 100 points for each 1 NOT in a triple
# 4. Add 50 points for each 5 NOT in a triple
def exact_same_function_as_score_but_more_readable(dice)
(1..6).map {|i| (dice.count(i)/3) * i * 100 }..inject {|a,b| a+b} + # score triples--the 1..6 map explodes to an array of scores for each triple, but inject collapses this back down to its sum
(dice.count(1)/3) * 900 + # score 1's bonus
(dice.count(1)%3)*100 + # score dangling 1's
(dice.count(5)%3)*50 # score dangling 2's
end
# ...
# regular tests in about_scoring_projects.rb omitted, here's the 2 I added:
# a "dangler" is a dice roll that does not make up a triple, so [1,1,1,1,3] has a dangling 1 and a dangling 3.
def test_score_of_huge_list_with_1_dangler
dice = [
1,1,1, # 1000
1,1,1, # 1000
1,1,1, # 1000
1, # 100
2,2,2, # 200
2,2,2, # 200
2,2,2, # 200
2, # 0
3,3,3, # 300
3,3,3, # 300
3,3,3, # 300
3, # 0
4,4,4, # 400
4,4,4, # 400
4,4,4, # 400
4, # 0
5,5,5, # 500
5,5,5, # 500
5,5,5, # 500
5, # 50
6,6,6, # 600
6,6,6, # 600
6,6,6, # 600
6 # 0
]
assert_equal 9150, score(dice)
end
def test_score_of_huge_list_with_2_danglers
dice = [
1,1,1, # 1000
1,1,1, # 1000
1,1,1, # 1000
1,1, # 200
2,2,2, # 200
2,2,2, # 200
2,2,2, # 200
2,2, # 0
3,3,3, # 300
3,3,3, # 300
3,3,3, # 300
3,3, # 0
4,4,4, # 400
4,4,4, # 400
4,4,4, # 400
4,4, # 0
5,5,5, # 500
5,5,5, # 500
5,5,5, # 500
5,5, # 100
6,6,6, # 600
6,6,6, # 600
6,6,6, # 600
6,6 # 0
]
assert_equal 9300, score(dice)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment