Skip to content

Instantly share code, notes, and snippets.

@rbobillot
Last active August 22, 2016 08:33
Show Gist options
  • Save rbobillot/d601c062a985d149ac730fc8a1cc36ee to your computer and use it in GitHub Desktop.
Save rbobillot/d601c062a985d149ac730fc8a1cc36ee to your computer and use it in GitHub Desktop.
object Test {
type R = BigInt
def main(av:Array[String]):Unit = {
//timed{ pascal(0, av.head.toInt) }
timed{ pascalV2(av.head.toInt) }
}
import collection.parallel.mutable.{ParArray => Array}
val zero = BigInt(0)
def pascalV2(n:Int):Unit = (1 to n).foldLeft(Array(1:R)){ case (acc, e) =>
//println(acc mkString " ")
(acc :+ zero).zip(zero +: acc).map{ case (l,r) => l + r }
}
def updateLine(line:Array[R]): Array[R] = {
val newline = BigInt(1) +: (line zip line.tail).map(t => t._1 + t._2) :+ BigInt(1)
//println(line mkString " ")
newline
}
def pascal(c:Int, r:Int)(implicit line:Array[R] = Array(1)): R =
if (0 < r) pascal(c, r-1)(updateLine(line)) else { updateLine(line); line(c) }
def timed[T](f: => T) = {
val s = System.currentTimeMillis
f
val e = System.currentTimeMillis
println(s"Done in ${(e-s)/1000.0} s")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment