Kotlin aggregate consecutive list elements

Viewed 135

I'd like to sum up consecutive numbers in a Kotlin list. If the list has a 0 then it should start summing up the numbers after 0. The result would be a list of sums. Basically sum up until the first 0 then until the next 0 and so forth. For example:

    val arr = arrayOf(1, 2, 0, 2, 1, 3, 0, 4)
    // list of sums =  [3,        6,       4]

At the moment I got it working with fold:

    val sums: List<Int> = arr.fold(listOf(0)) { sums: List<Int>, n: Int ->
        if (n == 0)
            sums + n
        else
            sums.dropLast(1) + (sums.last() + n)
    }
    

but I wonder if there is a simpler or more efficient way of doing this.

0 Answers
Related