Created
May 14, 2018 15:35
-
-
Save jesty/e2fe026bdce3ee58db19811f68c973c2 to your computer and use it in GitHub Desktop.
Fibonacci in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun seriesUntilPosition(position: Int): List<Int> { | |
return (1..position) | |
.map { Pair(0, 1) } | |
.fold(listOf(Pair(0, 1))) { acc, first -> | |
val last = acc.last() | |
acc + (Pair(last.second, last.first + last.second)) | |
} | |
.map { it.second } | |
} | |
//Oppure eliminando l'uso della classe Pair | |
fun seriesUntilPosition(position: Int): List<Int> = | |
(1..position) | |
.fold(listOf(0, 1)) | |
{ acc, _ -> acc + (acc.last() + acc[acc.lastIndex - 1]) } | |
.drop(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment