Last active
September 5, 2015 15:44
-
-
Save NigelThorne/513828 to your computer and use it in GitHub Desktop.
idea taken from http://xprogramming.com/articles/scala-bowling-i-think
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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") | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| } | |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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")
}
}
}