Skip to content

Instantly share code, notes, and snippets.

@jesty
Created May 14, 2018 15:35
Show Gist options
  • Save jesty/e2fe026bdce3ee58db19811f68c973c2 to your computer and use it in GitHub Desktop.
Save jesty/e2fe026bdce3ee58db19811f68c973c2 to your computer and use it in GitHub Desktop.
Fibonacci in Kotlin
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