Calculate Bowling Game Score
The Trade DeskSoftware Engineer · OnsiteLast 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
- 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.
- 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.
- 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.
- 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
rollslist 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?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.