Skip to content

Instantly share code, notes, and snippets.

@awead
Last active December 7, 2021 16:49
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 awead/c8fe830da9a67692331e9bb5c11978cb to your computer and use it in GitHub Desktop.
Save awead/c8fe830da9a67692331e9bb5c11978cb to your computer and use it in GitHub Desktop.
# @abstract Representation of a bowling frame. It can be any number of "throws" but a frame is complete if it is either
# open, a strike, or spare. Open frames occur when the player does not knock down all the pins within two throws. Closed
# frames mean all the pins were knocked down either with a strike or spare.
class Frame
attr_accessor :throws
def initialize
@throws = []
end
def closed?
strike? || spare?
end
def strike?
@throws[0] == 10
end
def spare?
@throws[0..1].sum == 10
end
def open?
@throws.count == 2 && !closed?
end
def score
if closed?
@throws[0..2].sum
else
@throws[0..1].sum
end
end
end
class Game
# @param throws [Array<Integer>] Listing of every ball rolled expressed as the number of pins knocked down.
# @param total_frames [Integer] Total number of frames in the game, defaults to 10.
def initialize(throws:, total_frames: 10)
@throws = throws
@total_frames = total_frames
end
def frames
accumulator = []
frame = Frame.new
throws.map.with_index do |shot, index|
frame.throws << shot
next unless (frame.open? || frame.closed?)
if frame.strike?
frame.throws += throws.slice((index + 1), 2)
elsif frame.spare?
frame.throws << throws[(index + 1)]
end
accumulator << frame
break if accumulator.count == total_frames
frame = Frame.new
end
accumulator
end
def tally
frames.map(&:score).sum
end
private
attr_reader :throws, :total_frames
end
game = Game.new(throws: [ 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 ])
puts game.tally
game = Game.new(throws: [5, 3, 7, 2, 10, 9, 0, 8, 1, 4, 4, 8, 2, 10, 9, 0, 9, 1, 7])
puts game.tally
game = Game.new(throws: [10, 7, 3, 7, 2, 9, 1, 10, 10, 10, 2, 3, 6, 4, 7, 3, 3])
puts game.tally
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment