Initial data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 72d218235f
commit f23f22d71c
199087 changed files with 3378941 additions and 0 deletions

View file

@ -0,0 +1,5 @@
def fib(i: Int): Int = i match {
case 0 => 0
case 1 => 1
case _ => fib(i - 1) + fib(i - 2)
}

View file

@ -0,0 +1 @@
lazy val fib: LazyList[Int] = 0 #:: 1 #:: fib.zip(fib.tail).map { case (a, b) => a + b }

View file

@ -0,0 +1,6 @@
import scala.annotation.tailrec
@tailrec
final def fib(x: Int, prev: BigInt = 0, next: BigInt = 1): BigInt = x match {
case 0 => prev
case _ => fib(x - 1, next, next + prev)
}

View file

@ -0,0 +1,13 @@
// Fibonacci using BigInt with LazyList.foldLeft optimized for GC (Scala v2.13 and above)
// Does not run out of memory for very large Fibonacci numbers
def fib(n: Int): BigInt = {
def series(i: BigInt, j: BigInt): LazyList[BigInt] = i #:: series(j, i + j)
series(1, 0).take(n).foldLeft(BigInt("0"))(_ + _)
}
// Small test
(0 to 13) foreach {n => print(fib(n).toString + " ")}
// result: 0 1 1 2 3 5 8 13 21 34 55 89 144 233

View file

@ -0,0 +1,6 @@
val it: Iterator[Int] = Iterator.iterate((0, 1)) { case (a, b) => (b, a + b) }.map(_._1)
def fib(n: Int): Int = it.drop(n).next()
// example:
println(it.take(13).mkString(",")) // prints: 0,1,1,2,3,5,8,13,21,34,55,89,144