Skip to content

Instantly share code, notes, and snippets.

@jbrechtel
Created February 27, 2011 04:28
Show Gist options
  • Save jbrechtel/845902 to your computer and use it in GitHub Desktop.
Save jbrechtel/845902 to your computer and use it in GitHub Desktop.
class BowlingGame
def initialize
@all_rolls = []
end
def roll(pins)
@all_rolls << pins
end
def score
sum(build_frame_scores(@all_rolls).flatten.slice(0,10))
end
def sum(list)
list.inject(0) { |total, i| total + i }
end
def build_frame_scores(rolls)
return [] if rolls.empty?
strike = rolls.first == 10
spare = rolls[0] + (rolls[1] || 0) == 10
if strike
[sum(rolls.slice(0,3)), build_frame_scores(rolls.drop(1))]
elsif spare
[sum(rolls.slice(0,3)), build_frame_scores(rolls.drop(2))]
else
[sum(rolls.slice(0,2)), build_frame_scores(rolls.drop(2))]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment