Skip to content

Instantly share code, notes, and snippets.

@redsquirrel
Created July 15, 2012 00:43
Show Gist options
  • Save redsquirrel/3114133 to your computer and use it in GitHub Desktop.
Save redsquirrel/3114133 to your computer and use it in GitHub Desktop.
In which I realize that the scoring logic for strikes and spares are the same. (3 consecutive balls)
require 'test/unit'
def score(*frames)
score = roll_count = 0
rolls = frames.flatten
frames.each do |frame|
if sum(frame) == 10
score += sum(next_three(rolls, roll_count))
else
score += sum(frame)
end
roll_count += frame.size
end
score
end
def next_three(rolls, roll_count)
rolls[roll_count, 3]
end
def sum(rolls)
rolls.inject{|sum,roll|sum+roll}
end
class BowlingTest < Test::Unit::TestCase
def test_1
assert_equal 9, score([5, 4])
end
def test_2
assert_equal 10, score([5, 4], [1, 0])
end
def test_spare
assert_equal 25, score([5, 5], [6, 3])
end
def test_strike
assert_equal 28, score([10], [6, 3])
end
def test_double_strike
assert_equal 60, score([3, 3], [10], [10], [6, 3])
end
def test_max_rolls
assert_equal 30, score(*(1..9).map{[0,0]}+[[10,10,10]])
end
def test_almost_perfect
assert_equal 279, score(*(1..9).map{[10]}+[[9,1,10]])
end
def test_perfect
assert_equal 300, score(*(1..9).map{[10]}+[[10,10,10]])
end
end
@dancardella
Copy link

Great challenge Dave. Made me aware of how much I could DRY my code out. My response here: git://gist.github.com/3163121.git Danny

@redsquirrel
Copy link
Author

redsquirrel commented Jul 23, 2012 via email

@dancardella
Copy link

dancardella commented Jul 25, 2012 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment