Skip to content

Instantly share code, notes, and snippets.

@jbrechtel
Created February 23, 2011 01:37
Show Gist options
  • Save jbrechtel/839820 to your computer and use it in GitHub Desktop.
Save jbrechtel/839820 to your computer and use it in GitHub Desktop.
import scala.collection.mutable._
class BowlingGame(val reverseRolls: List[Int]) {
def roll(pins: Int) = {
if(pins == 10)
new BowlingGame(0 :: pins :: reverseRolls)
else
new BowlingGame(pins :: reverseRolls)
}
lazy val rolls = reverseRolls.reverse
def score() = {
(0 to 9).map(_ * 2).foldLeft(0)((score, frameIndex) => {
if(isStrike(frameIndex))
score + 10 + strikeBonus(frameIndex)
else if(isSpare(frameIndex))
score + 10 + spareBonus(frameIndex)
else
score + sumOfBallsInFrame(frameIndex)
})
}
private def isStrike(index: Int) = rolls(index) == 10
private def isSpare(index: Int) = sumOfBallsInFrame(index) == 10
private def sumOfBallsInFrame(index: Int) = rolls(index) + rolls(index+1)
private def spareBonus(index: Int) = rolls(index+2)
private def strikeBonus(index: Int) = {
if(isStrike(index+2)) rolls(index+2) + rolls(index+4) else rolls(index+2) + rolls(index+3)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment