Katkat

Calculate Bowling Game Score

The Trade DeskSoftware Engineer · Onsite

Last updated

This problem tests your ability to manage state and look-ahead logic when processing a sequence of events (bowling rolls) governed by specific conditional scoring rules.

Bowling Game Scorer

Implement a scoring system for a standard game of ten-pin bowling. A game consists of 10 frames. In each frame, a player has up to two rolls to knock down 10 pins.

Scoring Rules

  1. Open Frame: If the sum of pins knocked down in two rolls is less than 10, the score for the frame is the sum of those rolls.
  2. Spare: If all 10 pins are knocked down in two rolls, the score for the frame is 10 plus the number of pins knocked down in the next roll.
  3. Strike: If 10 pins are knocked down on the first roll, the frame ends immediately. The score is 10 plus the sum of the next two rolls.
  4. The 10th Frame: If a player rolls a strike or spare in the 10th frame, they get extra rolls to complete the frame. A strike in the 10th frame allows two additional rolls; a spare allows one additional roll. These extra rolls are only used to calculate the 10th frame score and do not constitute additional frames.

Task

Create a function calculate_score(rolls) that takes a list of integers representing the number of pins knocked down in each roll and returns the total score of the game.

Examples

# Example 1: All gutter balls
calculate_score([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) 
# Output: 0

# Example 2: Simple spares
# Frame 1: 5+5 + (3) = 13
# Frame 2: 3+4 = 7
# Total: 20
calculate_score([5, 5, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
# Output: 20

Constraints

  • rolls list contains only valid integers [0, 10].
  • The input is guaranteed to represent a completed game.

Hints

Hint 1

Instead of trying to calculate frame scores on the fly, iterate through the list using an index pointer to track the current frame start.

Hint 2

For strikes, you need to access the values at `index + 1` and `index + 2`; for spares, access `index + 2`.

Hint 3

The 10th frame is a special case because it can contain up to three rolls; verify if your logic correctly avoids creating an '11th frame' error.

Follow-up questions

  • How would you modify your code to provide a running score (the score after each frame) instead of just the final total?
  • What input validation would you add to ensure a sequence of rolls is a physically possible game?
  • How does the time and space complexity of your solution change if the game had N frames instead of 10?