Skip to content

Instantly share code, notes, and snippets.

@NigelThorne
Last active September 5, 2015 15:44
Show Gist options
  • Save NigelThorne/513828 to your computer and use it in GitHub Desktop.
Save NigelThorne/513828 to your computer and use it in GitHub Desktop.
class Game(rolls: List[Int]) {
def score:Int = score(rolls, 10)
private def score(rolls:List[Int], index:Int):Int = {
if (index == 0) return 0
rolls match {
case 10 :: second :: third :: rest
=> 10 + second + third + score(second :: third :: rest, index-1)
case first :: second :: third :: rest if first + second == 10
=> 10 + third + score(third :: rest, index-1)
case first :: second :: rest
=> first + second + score(rest, index-1)
case List()
=> error("too few frames")
}
}
}
object Game {
abstract class Frame { def score : Int }
case object LastFrame extends Frame { def score = 0 }
case class FrameList(total:Int, next:Frame) extends Frame {
def score = total + next.score
}
def fromRolls(remainingrolls: List[Int]): Frame = fromRolls(remainingrolls, 10)
private def fromRolls(remainingrolls: List[Int], index:Int): Frame = {
if (index == 0) return LastFrame
remainingrolls match {
case 10 :: b :: c :: rest => FrameList(10+b+c, fromRolls(b::c::rest, index-1))
case a :: b :: c :: rest if a+b == 10 => FrameList(10+c, fromRolls(c :: rest, index-1))
case a :: b :: rest => FrameList(a + b, fromRolls(rest, index-1))
case List() => LastFrame
}
}
}
class Game(val frames:Game.Frame) {
def this(rolls: List[Int]) = this(Game.fromRolls(rolls))
def score = frames.score
}
@NigelThorne
Copy link
Author

I used Game 'object' to allow me to generate a class that holds frames instead of rolls.

The fromRolls method only allows 10 frames and uses pattern matching of the list of rolls to generate frames correctly scored.

case Link() matches the empty list... it may be more correct for it to throw an error instead of succeed as this approach is intended only to score valid complete games.

The game class has an overloaded constructor that triggers the conversion of rolls into frames.

@NigelThorne
Copy link
Author

Here is a simple functional version

class Game(rolls: List[Int]) {
def score:Int = score(rolls, 10)
private def score(rolls:List[Int], index:Int):Int = {
if (index == 0) return 0
rolls match {
case 10 :: second :: third :: rest
=> 10 + second + third + score(second :: third :: rest, index-1)
case first :: second :: third :: rest if first + second == 10
=> 10 + third + score(third :: rest, index-1)
case first :: second :: rest
=> first + second + score(rest, index-1)
case List()
=> error("too few frames")
}
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment