Is there a functional way to map a list (N elements) to a list of sums of adjacent elements (N - 1 elements) in Kotlin?

52 views Asked by At

If it is possible using reduce/fold or other functional ways then I cannot find out how to do that. I need to somehow transform a list of let's say: 1, 2, 5, 2 to 3 (1+2), 7 (2+5), 7 (5+2)

I understand the problem is that reduce/fold iterate over adjacent elements but it is only one of the elements that is used with the result of reducing the previous. If there were a way to iterate over overlapping/intersecting pairs then it would allow for what I need.

2

There are 2 answers

0
Leviathan On BEST ANSWER

What you need is a sliding window of two elements while iterating over the list. You can do it in Kotlin like this:

val result = listOf(1, 2, 5, 2)
    .windowed(2) {
        it.sum()
    }

result now contains the list [3, 7, 7].

0
broot On

If we target specifically pairs of adjacent items (and not e.g. triples), then Kotlin provides the zipWithNext function which does exactly this:

listOf(1, 2, 5, 2).zipWithNext(Int::plus) // [3, 7, 7]