Skip to content

Instantly share code, notes, and snippets.

@Odomontois
Last active January 2, 2016 23:49
Show Gist options
  • Save Odomontois/8378557 to your computer and use it in GitHub Desktop.
Save Odomontois/8378557 to your computer and use it in GitHub Desktop.
import scala.collection.mutable
/**
* User: Oleg
* Date: 1/12/14
* Time: 3:32 AM
*/
object Probability {
def main(args: Array[String]) {
println(prob[Int, Double](.5, .8, 13, 10, 0))
println(prob[BigInt, BigDecimal](.5, .8, 13, 10, 0))
}
object prob {
def apply[N, R](p: R, q: R, x: N, y: N, used: N)(implicit f: Fractional[R], num: Numeric[N]) =
new Calculation(p, q)(f, num)(x, y, used)
class Calculation[N, R](p: R, q: R)(implicit f: Fractional[R], num: Numeric[N]) {
import f._
val `-1` = num.fromInt(-1)
val `0` = num.zero
val cache = mutable.Map.empty[(N,N,N),R]
def apply(x: N, y: N, used: N): R = cache.getOrElseUpdate((x, y, used),(x, y, used) match {
case (`0`, `0`, _) => one
case (_, `-1`, _) | (`-1`, _, _) => zero
case (_, _, `0`) => apply(x --, y, `0`) * p + apply(x, y --, `0`) * (one - p)
case _ => apply(x --, y, used --) * q + apply(x, y --, used --) * (one - q)
})
implicit class NumericExtra(t: N) {
import num._
def -- = t - one
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment