Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
.DS_Store
.idea/shelf
.idea
/android.tests.dependencies
/confluence/target
/dependencies/repo
Expand Down
32 changes: 32 additions & 0 deletions src/main/kotlin/dynamicProgramming/Fibonacci.kt
Original file line number Diff line number Diff line change
@@ -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) }