Search code examples
kotlinreducefold

How I can return IntArray with reduce or fold?


I have the following data for my task:

Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].

As u see, I need to return IntArray, the first thing I used was runningReduce() , but this function is used in the version of Kotlin 1.4.30.

fun runningSum(nums: IntArray): IntArray {
    return nums.runningReduce { sum, element -> sum + element }.toIntArray()
}

Yes, this solution works, but how can I solve the same problem using reduce() or fold()?


Solution

  • Mafor is right, fold() is not a good choice when producing a collection because it copies the collection every time so you need to workaround with mutable collections, which defeats the point of the functional style.

    If you really want to work with arrays, which are mutable, doing it the old fashioned procedural way may be best:

    val array = intArrayOf(1, 2, 3, 4)
    for (i in array.indices.drop(1)) {
        array[i] += array[i - 1]
    }
    println(array.joinToString(", "))
    

    Here's a slightly modified version of Mafor's answer that gives you an IntArray and avoids the use of multiple statements - it still uses the mutable list though:

    val input = intArrayOf(1, 2, 3, 4)
    val output = input.fold(mutableListOf(0)) { acc, cur ->
        acc.apply { add(last() + cur) }
    }.drop(1).toIntArray()
    
    println(output.joinToString(", "))
    

    Both of these print 1, 3, 6, 10.