🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of Ric0chet

Ric0chet's solution

to Bowling in the Scala Track

Published at Nov 08 2019 · 1 comment
Instructions
Test suite
Solution

Score a bowling game.

Bowling is a game where players roll a heavy ball to knock down pins arranged in a triangle. Write code to keep track of the score of a game of bowling.

Scoring Bowling

The game consists of 10 frames. A frame is composed of one or two ball throws with 10 pins standing at frame initialization. There are three cases for the tabulation of a frame.

  • An open frame is where a score of less than 10 is recorded for the frame. In this case the score for the frame is the number of pins knocked down.

  • A spare is where all ten pins are knocked down by the second throw. The total value of a spare is 10 plus the number of pins knocked down in their next throw.

  • A strike is where all ten pins are knocked down by the first throw. The total value of a strike is 10 plus the number of pins knocked down in the next two throws. If a strike is immediately followed by a second strike, then the value of the first strike cannot be determined until the ball is thrown one more time.

Here is a three frame example:

Frame 1 Frame 2 Frame 3
X (strike) 5/ (spare) 9 0 (open frame)

Frame 1 is (10 + 5 + 5) = 20

Frame 2 is (5 + 5 + 9) = 19

Frame 3 is (9 + 0) = 9

This means the current running total is 48.

The tenth frame in the game is a special case. If someone throws a strike or a spare then they get a fill ball. Fill balls exist to calculate the total of the 10th frame. Scoring a strike or spare on the fill ball does not give the player more fill balls. The total value of the 10th frame is the total number of pins knocked down.

For a tenth frame of X1/ (strike and a spare), the total value is 20.

For a tenth frame of XXX (three strikes), the total value is 30.

Requirements

Write code to keep track of the score of a game of bowling. It should support two operations:

  • roll(pins : int) is called each time the player rolls a ball. The argument is the number of pins knocked down.
  • score() : int is called only at the very end of the game. It returns the total score for that game.

The Scala exercises assume an SBT project scheme. The exercise solution source should be placed within the exercise directory/src/main/scala. The exercise unit tests can be found within the exercise directory/src/test/scala.

To run the tests simply run the command sbt test in the exercise directory.

Please see the learning and installation pages if you need any help.

Source

The Bowling Game Kata at but UncleBob http://butunclebob.com/ArticleS.UncleBob.TheBowlingGameKata

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

BowlingSuite.scala

import org.scalatest.{Matchers, FunSuite}

/** @version 1.0.1 */
class BowlingTest extends FunSuite with Matchers {

  test("should be able to score a game with all zeros") {
    val score = List(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).score()
    score should be (Right(0))
  }

  test("should be able to score a game with no strikes or spares") {
    pending
    val score = List(3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).score()
    score should be (Right(90))
  }

  test("a spare followed by zeros is worth ten points") {
    pending
    val score = List(6, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).score()
    score should be (Right(10))
  }

  test("points scored in the roll after a spare are counted twice") {
    pending
    val score = List(6, 4, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).score()
    score should be (Right(16))
  }

  test("consecutive spares each get a one roll bonus") {
    pending
    val score = List(5, 5, 3, 7, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).score()
    score should be (Right(31))
  }

  test("a spare in the last frame gets a one roll bonus that is counted once") {
    pending
    val score = List(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 7).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).score()
    score should be (Right(17))
  }

  test("a strike earns ten points in a frame with a single roll") {
    pending
    val score = List(10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).score()
    score should be (Right(10))
  }

  test("points scored in the two rolls after a strike are counted twice as a bonus") {
    pending
    val score = List(10, 5, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).score()
    score should be (Right(26))
  }

  test("consecutive strikes each get the two roll bonus") {
    pending
    val score = List(10, 10, 10, 5, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).score()
    score should be (Right(81))
  }

  test("a strike in the last frame gets a two roll bonus that is counted once") {
    pending
    val score = List(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 7, 1).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).score()
    score should be (Right(18))
  }

  test("rolling a spare with the two roll bonus does not get a bonus roll") {
    pending
    val score = List(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 7, 3).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).score()
    score should be (Right(20))
  }

  test("strikes with the two roll bonus do not get bonus rolls") {
    pending
    val score = List(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).score()
    score should be (Right(30))
  }

  test("a strike with the one roll bonus after a spare in the last frame does not get a bonus") {
    pending
    val score = List(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 10).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).score()
    score should be (Right(20))
  }

  test("all strikes is a perfect game") {
    pending
    val score = List(10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).score()
    score should be (Right(300))
  }

  test("rolls cannot score negative points") {
    pending
    val score = List().foldLeft(Bowling())((acc, roll) => acc.roll(roll)).roll(-1).score()
    score.isLeft should be (true)
  }

  test("a roll cannot score more than 10 points") {
    pending
    val score = List().foldLeft(Bowling())((acc, roll) => acc.roll(roll)).roll(11).score()
    score.isLeft should be (true)
  }

  test("two rolls in a frame cannot score more than 10 points") {
    pending
    val score = List(5).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).roll(6).score()
    score.isLeft should be (true)
  }

  test("bonus roll after a strike in the last frame cannot score more than 10 points") {
    pending
    val score = List(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).roll(11).score()
    score.isLeft should be (true)
  }

  test("two bonus rolls after a strike in the last frame cannot score more than 10 points") {
    pending
    val score = List(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 5).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).roll(6).score()
    score.isLeft should be (true)
  }

  test("two bonus rolls after a strike in the last frame can score more than 10 points if one is a strike") {
    pending
    val score = List(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 6).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).score()
    score should be (Right(26))
  }

  test("the second bonus rolls after a strike in the last frame cannot be a strike if the first one is not a strike") {
    pending
    val score = List(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 6).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).roll(10).score()
    score.isLeft should be (true)
  }

  test("second bonus roll after a strike in the last frame cannot score more than 10 points") {
    pending
    val score = List(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).roll(11).score()
    score.isLeft should be (true)
  }

  test("an unstarted game cannot be scored") {
    pending
    val score = List().foldLeft(Bowling())((acc, roll) => acc.roll(roll)).score()
    score.isLeft should be (true)
  }

  test("an incomplete game cannot be scored") {
    pending
    val score = List(0, 0).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).score()
    score.isLeft should be (true)
  }

  test("cannot roll if game already has ten frames") {
    pending
    val score = List(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).roll(0).score()
    score.isLeft should be (true)
  }

  test("bonus rolls for a strike in the last frame must be rolled before score can be calculated") {
    pending
    val score = List(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).score()
    score.isLeft should be (true)
  }

  test("both bonus rolls for a strike in the last frame must be rolled before score can be calculated") {
    pending
    val score = List(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).score()
    score.isLeft should be (true)
  }

  test("bonus roll for a spare in the last frame must be rolled before score can be calculated") {
    pending
    val score = List(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3).foldLeft(Bowling())((acc, roll) => acc.roll(roll)).score()
    score.isLeft should be (true)
  }
}
import scala.collection.mutable.ListBuffer
//  11-07-19

// 100 ms -- using matching (calculates during score)
case class Bowling(rolls: List[Int] = List()) {
  type Result = Either[String, Int]

  def roll(pins: Int): Bowling = copy(rolls :+ pins)

  def score(): Result = {
    def calc(rolls: Seq[Int], fr: Int = 1, total: Int = 0): Result =
      if (fr == 10) rolls match {
        case 10 :: 10 :: c :: x if x.isEmpty => Right(total + 20 + c)
        case 10 :: 10 :: _                   => Left("Strike bonus roll missing")
        case 10 :: b :: c :: _ if b + c > 10 => Left(s"Invalid frame total: ${b + c}")
        case 10 :: b :: c :: x if x.isEmpty  => Right(total + 10 + b + c)
        case a :: b :: c :: x if x.isEmpty && a + b == 10 => Right(total + 10 + c)
        case a :: b :: _ if a + b == 10      => Left("Spare bonus roll missing")
        case a :: b :: x if x.isEmpty        => Right(total + a + b)
        case _                               => Left("10th frame error")
      }
      else rolls match {
        case 10 :: x                    => calc(x, fr + 1, total + 10 + x.take(2).sum)
        case a :: b :: x if a + b == 10 => calc(x, fr + 1, total + 10 + x.head)
        case a :: b :: x if a + b > 10  => Left(s"Invalid frame total: ${a + b}")
        case a :: b :: x                => calc(x, fr + 1, total + a + b)
        case _                          => Left("Rolls missing")
      }

    if (rolls.exists(_ < 0) || rolls.exists(_ > 10)) Left("Invalid pin total")
    else calc(rolls)
  }
}


// 98 ms -- using brute-force (calculates during rolls)
case class Bowling2(rolls: List[Int] = List()) {
  private var frames = ListBuffer[Int]()
  private var active = ListBuffer[Int]()
  private var error = ""

  def roll(pins: Int): Bowling2 = {
    if (pins < 0 || pins > 10 || gameOver) error = "Roll Error"
    else {
      var acc = 0
      active += pins

      // Strikes
      if (active.length == 3 && isStrike) {
        if (active(1) != 10 && active(1) + active(2) > 10)
          error = "Strike Error"
        else {
          acc = active.sum
          frames += acc
          active.remove(0)
        }
      }

      // Spares
      if (active.length == 3 && isSpare) {
        acc = active.sum
        frames += acc
        active.remove(0, 2)
      }

      // Full frames
      if (active.length == 2 && !(gameOver || isStrike || isSpare)) {
        acc = active.sum
        if (acc > 10) error = "Frame Error"
        else {
          frames += acc
          active.remove(0, 2)
        }
      }
    }

    this
  }

  def score(): Either[String, Int] =
    if (!error.isBlank) Left(error)
    else if (!gameOver) Left("Score Error")
    else Right(frames.sum)

  private def isStrike: Boolean = active.head == 10

  private def isSpare: Boolean = active.take(2).sum == 10

  private def gameOver: Boolean = frames.length == 10
}

Community comments

Find this solution interesting? Ask the author a question to learn more.
Avatar of Ric0chet

That second method was ported from my solution on the Bash track.

Ric0chet's Reflection

Includes two solutions for benchmark comparison (one calculates in score, the other in roll). This time the match-case method was just as fast as brute-force.