Skip to content

Instantly share code, notes, and snippets.

@ybonnel
Created January 31, 2013 03:35
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 ybonnel/4679812 to your computer and use it in GitHub Desktop.
Save ybonnel/4679812 to your computer and use it in GitHub Desktop.
Scalaskel en scala
package models.scalaskel
import play.api.libs.json._
import play.api.Logger
case class Change(foo:Int, bar:Int, qix:Int, baz:Int) {
def this() = this(0, 0, 0, 0)
def this(change:Change, coin:Coin) = this(
if (coin.isFoo) change.foo + 1 else change.foo,
if (coin.isBar) change.bar + 1 else change.bar,
if (coin.isQix) change.qix + 1 else change.qix,
if (coin.isBaz) change.baz + 1 else change.baz
)
def toJson:JsObject = {
val fields = Seq("foo" -> foo,
"bar" -> bar,
"qix" -> qix,
"baz" -> baz).filter( value => value._2 != 0)
return JsObject(fields.map(f => (f._1, JsNumber(f._2))))
}
}
package models.scalaskel
case class Coin(value:Int) {
def canPay(centsToPay:Int):Boolean = centsToPay >= value
def isFoo:Boolean = value == 1
def isBar:Boolean = value == 7
def isQix:Boolean = value == 11
def isBaz:Boolean = value == 21
}
object Coin {
def allCoin = Seq(
Coin(1),
Coin(7),
Coin(11),
Coin(21)
)
}
package controllers
import models.scalaskel.{Coin, Change}
import play.api.mvc._
import play.api.libs.json._
object Scalaskel extends Controller {
def calculate(cents: Int, currentChange: Option[Change], lastCoin: Coin): List[Change] = {
if (cents == 0) {
return List(currentChange).filter(change => change.isDefined).map(change => change.get)
}
var changes: List[Change] = List()
Coin.allCoin.filter(aCoin => aCoin.value >= lastCoin.value && aCoin.canPay(cents)).foreach(
aCoin => {
val newChange = new Change(currentChange.getOrElse(new Change()), aCoin)
changes = changes ::: calculate(cents - aCoin.value, Option(newChange), aCoin)
}
)
return changes
}
def change(cents: Integer) = Action {
val changes = calculate(cents, Option.empty, Coin(1))
val jsonResult = changes.map(change => change.toJson)
Ok(Json.toJson(jsonResult))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment