Last active
April 5, 2021 10:38
-
-
Save rakshakhegde/1ef964a2bfdde0492fd03490dfb67849 to your computer and use it in GitHub Desktop.
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
import kotlin.reflect.KFunction1 | |
import kotlin.test.assertEquals | |
fun main() { | |
assertSums(::makeSum) | |
assertSums(::makeSum2) | |
assertSums(::makeSum3) | |
} | |
fun assertSums(kFunction1: KFunction1<List<Int>, List<Int>>) { | |
assertEquals( | |
actual = kFunction1(listOf(1, 2, 3, 4)), | |
expected = listOf(1, 3, 6, 10) | |
) | |
assertEquals( | |
actual = kFunction1(emptyList()), | |
expected = emptyList() | |
) | |
} | |
fun makeSum(list: List<Int>): List<Int> { | |
if (list.isEmpty()) return emptyList() | |
val summed = IntArray(list.size) | |
summed[0] = list[0] | |
for (i in 1 until list.size) { | |
summed[i] = list[i] + summed[i - 1] | |
} | |
return summed.asList() | |
} | |
fun makeSum2(list: List<Int>): List<Int> { | |
return indexedSequence(list.firstOrNull()) { index, prev -> | |
prev + list[index] | |
} | |
.take(list.size) | |
.toList() | |
} | |
inline fun <T : Any> indexedSequence( | |
seed: T?, | |
crossinline nextFunction: (Int, T) -> T? | |
): Sequence<T> { | |
var index = 0 | |
return generateSequence(seed) { prev -> | |
index++ | |
nextFunction(index, prev) | |
} | |
} | |
fun makeSum3(list: List<Int>): List<Int> { | |
if (list.isEmpty()) return emptyList() | |
val size = list.size | |
val summed = IntArray(size) | |
tailrec fun sumIt(index: Int) { | |
if (index == size) return | |
summed[index] = summed[index - 1] + list[index] | |
sumIt(index + 1) | |
} | |
summed[0] = list[0] | |
sumIt(1) | |
return summed.toList() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment