Skip to content

Instantly share code, notes, and snippets.

@MrJaba
Created February 26, 2012 14:05
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 MrJaba/1916977 to your computer and use it in GitHub Desktop.
Save MrJaba/1916977 to your computer and use it in GitHub Desktop.
Bowling Kata
import scala.collection.mutable.ArrayBuffer
object BowlingScorer extends App {
val testFrame = "XXXXXXXXXXXX"
//val testFrame = "9-9-9-9-9-9-9-9-9-9-"
//val testFrame = "5/5/5/5/5/5/5/5/5/5/5"
val frames = new ArrayBuffer[Frame]()
var frameCount = 0
for( roll <- testFrame ){
if(frames.length == 0 || frames.last.complete()){
frames += new Frame(roll, frameCount)
frameCount+=1
}
else
frames.last.addPins(roll)
}
val score = frames.foldLeft(0){(sum, frame) => sum + frame.score(testFrame)}
println( score )
}
class Frame(initialPins:Char, frameCount:Int){
var isSpare = false
var isStrike = initialPins == 'X'
var pins = new ArrayBuffer[Int]()
pins += pinCount(initialPins)
var rolls = 1
val frame = frameCount
def pinCount(initialPins:Char): Int = {
initialPins match{
case 'X' => 10
case '-' => 0
case '/' => 10 - pins.first
case _ => Integer.parseInt(initialPins.toString())
}
}
def complete() : Boolean = {
frame < 9 && (rolls == 2 || pinSum() == 10)
}
def addPins(p:Char) {
if(rolls < 2)
isSpare = p == '/'
pins += pinCount(p)
rolls += 1
}
def pinSum(): Int = {
if(isStrike || isSpare)
10
else
pins(0) + (if(pins.length == 1) 0 else pins(1))
}
def score(rolls:String) : Int = {
var score = pinSum()
if(isStrike){
score += pinCount(rolls(frame+1)) + pinCount(rolls(frame+2))
}
if(isSpare){
score += pinCount(rolls(frame+1))
}
score
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment