diff --git a/src/main/scala/Others/Fibbonacci.scala b/src/main/scala/Others/Fibbonacci.scala new file mode 100644 index 0000000..2ac9e22 --- /dev/null +++ b/src/main/scala/Others/Fibbonacci.scala @@ -0,0 +1,46 @@ +package Others + +import scala.annotation.tailrec + +/** + * Assuming that sequence starts from 0 + */ +object Fibbonacci { + /** + * Standard recursion solution, + * + * @param n - which Fibbonacci number + * @return + */ + def nthNumberRecursive(n: Int): Int = { + if (n <= 1) 1 + else nthNumberRecursive(n - 1) + nthNumberRecursive(n - 2) + } + + def nthNumberIterative(n: Int): Int = { + var first = 1 + var second = 1 + if (n == 0) first + else if (n == 1) second + else { + var third: Int = first + second + for (i <- 3 to n) { + first = second + second = third + third = first + second + } + third + } + } + + def nthNumberTailRec(n: Int): Int = { + @tailrec + def nthNumber(n: Int, current: Int, temp: Int): Int = n match { + case 0 => current + case _ => nthNumber(n - 1, temp, current + temp) + } + + nthNumber(n, 1, 1) + } + +} diff --git a/src/test/scala/Others/FibbonacciSpec.scala b/src/test/scala/Others/FibbonacciSpec.scala new file mode 100644 index 0000000..e457f86 --- /dev/null +++ b/src/test/scala/Others/FibbonacciSpec.scala @@ -0,0 +1,42 @@ +package Others + +import org.scalatest.FlatSpec + +class FibbonacciSpec extends FlatSpec { + + "recursive solution" should "start from 1" in { + assert(Fibbonacci.nthNumberRecursive(0) === 1) + } + + it should "calculate some fibbonacci number" in { + assert(Fibbonacci.nthNumberRecursive(4) === 5) + } + + it should "return sum of two previous numbers" in { + for (i <- 2 to 10) assert(Fibbonacci.nthNumberRecursive(i) === Fibbonacci.nthNumberRecursive(i - 1) + Fibbonacci.nthNumberRecursive(i - 2)) + } + + "iterative solution" should "start from 1" in { + assert(Fibbonacci.nthNumberIterative(0) === 1) + } + + it should "calculate some fibbonacci number" in { + assert(Fibbonacci.nthNumberIterative(4) === 5) + } + + it should "return sum of two previous numbers" in { + for (i <- 2 to 20) assert(Fibbonacci.nthNumberIterative(i) === Fibbonacci.nthNumberIterative(i - 1) + Fibbonacci.nthNumberIterative(i - 2)) + } + + "tail recursive solution" should "start from 1" in { + assert(Fibbonacci.nthNumberTailRec(0) === 1) + } + + it should "calculate some fibbonacci number" in { + assert(Fibbonacci.nthNumberTailRec(4) === 5) + } + + it should "return sum of two previous numbers" in { + for (i <- 2 to 20) assert(Fibbonacci.nthNumberTailRec(i) === Fibbonacci.nthNumberTailRec(i - 1) + Fibbonacci.nthNumberTailRec(i - 2)) + } +}