Skip to content

Instantly share code, notes, and snippets.

@mayonesa
Last active February 4, 2022 17:25
Show Gist options
  • Save mayonesa/e906877ef1b24a7c6191d95915e42959 to your computer and use it in GitHub Desktop.
Save mayonesa/e906877ef1b24a7c6191d95915e42959 to your computer and use it in GitHub Desktop.
The partition function at 100
object P100 extends App {
private def p(bal: Int, summand: Int, m: Map[(Int, Int), Int]): (Int, Map[(Int, Int), Int]) =
if (bal < 0 || summand == 100) (0, m)
else if (bal == 0) (1, m)
else {
val (nSumsWithSummand, m1) = p0(bal - summand, summand, m)
val (nSumsWithoutSummand, m2) = p0(bal, summand + 1, m1)
(nSumsWithSummand + nSumsWithoutSummand, m2)
}
private def p0(b: Int, s: Int, m: Map[(Int, Int), Int]) =
m.get((b, s)) match {
case None =>
val (nsws, m0) = p(b, s, m)
(nsws, m0 + ((b, s) -> nsws))
case Some(cachedNSums) => (cachedNSums, m)
}
println(p(100, 1, Map.empty)._1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment