diff --git a/.gitignore b/.gitignore index 86b5e58..51d58df 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ .DS_Store -.idea/shelf +.idea /android.tests.dependencies /confluence/target /dependencies/repo diff --git a/src/main/kotlin/dynamicProgramming/Fibonacci.kt b/src/main/kotlin/dynamicProgramming/Fibonacci.kt new file mode 100644 index 0000000..a6f5bbc --- /dev/null +++ b/src/main/kotlin/dynamicProgramming/Fibonacci.kt @@ -0,0 +1,32 @@ +package dynamicProgramming + +/** + * The following example is taken from Ken Kousen book "Kotlin Cookbook. A Problem-Focused Approach" + */ + +/** + * Get Fibonacci sequence + */ +fun fibonacciSequence() = sequence { + var terms = Pair(0, 1) + while (true) { + yield(terms.first) + terms = terms.second to terms.first + terms.second + } +} + + +/** + * Get n Fibonacci number + */ +fun fibonacciFold(n: Int) = + (2 until n).fold(1 to 1) { (prev, curr), _ -> + curr to (prev + curr) }.second + +/** + * Get n Fibonacci number + */ +@JvmOverloads +tailrec fun fibonacci(n: Int, a: Int = 0, b: Int = 1): Int = + when (n) { 0 -> a 1 -> b + else -> fibonacci(n - 1, b, a + b) } \ No newline at end of file