My solution to Sliding window challenge

This is my solution to this callenge:

val valuesToAdd = listOf(1,18,73,3,44,6,1,33,2,22,5,7)
println(valuesToAdd.filter{ it >= 5 }.chunked(2).map{ it[0] * it[1]}.fold(0) { accumulator, number -> accumulator + number })

I hope this will be useful to somebody.

Cheers

3 Likes

I came up with about the same thing, the only difference being the use of “sum()” instead of “fold(0) {a, n → a + n}” as the last function in the chain:

val valuesToAdd = listOf(1, 18, 73, 3, 44, 6, 1, 33, 2, 22, 5, 7)
println(valuesToAdd.filter { it >= 5 }.chunked(2){ it[0] * it[1] }.sum())

4 Likes

Another way to solve the challenge:

val valuesToAdd = listOf(1, 18, 73, 3, 44, 6, 1, 33, 2, 22, 5, 7)
val slidingWindow = valuesToAdd.filter { it >= 5 }.windowed(2, 2) {
    it.fold(1) { a, b -> a * b }
}.sum()
println(slidingWindow)
val res = valuesToAdd.filter { it >= 5 }.chunked(2).sumOf { it[0] * it[1] }
println(res)