Skip to content

Instantly share code, notes, and snippets.

@ahoy-jon
Created August 16, 2018 13:16
Show Gist options
  • Save ahoy-jon/64cac4f90766cc174ecad267999a70bc to your computer and use it in GitHub Desktop.
Save ahoy-jon/64cac4f90766cc174ecad267999a70bc to your computer and use it in GitHub Desktop.
object Bowling {
type Coef = (Int, Int)
implicit class Tuple2Ops[A, B](val t: (A, B)) extends AnyVal {
def map_1[C](f: A => C): (C, B) = (f(t._1), t._2)
def map_2[C](f: B => C): (A, C) = (t._1, f(t._2))
}
case class TempScore(scoreTotal: Int, coef: Coef, isNewTurn: Boolean, nbTurn: Int, lastShot: Option[Int]) {
def addShot(shot: Int): TempScore = {
(isNewTurn, lastShot.getOrElse(0) + shot == 10) match {
//STRIKE
case (true, true) => updateScore(shot).incNextShot.incSecondShot.nextTurn
//SPARE
case (false, true) => updateScore(shot).incNextShot.nextTurn
//A Shot
case (true, false) => updateScore(shot)
//END OF TURN
case (false, false) => updateScore(shot).nextTurn
}
}
private def incSecondShot: TempScore = copy(coef = coef.map_1(_ + 1))
private def incNextShot: TempScore = copy(coef = coef.map_2(_ + 1))
private def updateScore(shot: Int): TempScore = copy(scoreTotal = scoreTotal + shot * coef._1, coef = (coef._2, 1), lastShot = Some(shot), isNewTurn = false)
private def nextTurn: TempScore = copy(isNewTurn = true, nbTurn = nbTurn + 1, lastShot = None)
}
val init: TempScore = TempScore(scoreTotal = 0, coef = (1, 1), isNewTurn = true, nbTurn = 0, lastShot = None)
def score(shots: Integer*): Integer = {
shots.foldLeft(init)(_ addShot _).scoreTotal
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment