`input.map { it.sum() }`?
# announcements
d
input.map { it.sum() }
?
🚫 1
a
that would give me the "horizontal sum", no?
d
Oh, I see. I misunderstood your problem. I can't think of a good way to do what you want without many list copies.
m
So you kinda want this, right?
[1 + 4 + 7, 2 + 5 + 8, 3 + 6 + 9] = [12, 15, 18]
a
yes, correct
m
And all lists are of the same length?
a
Sure
b
maybe this?
Copy code
val input: List<List<Int>> = listOf(listOf(1, 2, 3), listOf(4, 5, 6))

        input.reduce { acc, list -> acc.map { it + list[acc.indexOf(it)] } }
Copy code
result - [5, 7, 9]
m
This works, but it creates a lot of intermediate lists:
Copy code
input.fold(List(sublistLength) { 0 }) { acc, list ->
    acc.zip(list).map { (a, b) -> a + b }
}
Another way would be to write a transpose-function (google it), and then sum each line in the resulting list.
input.transpose().map { it.sum() }
a
This is what I have at the moment (supports variable length rows) but return buffer and for loop leave a sour taste
Copy code
fun sumColumns(data: List<List<Double>>): List<Double> {
    val longest = max(data.map { it.size }) - 1
    
    val result = mutableListOf<Double>()
    
    for (index in 0..longest) {
        val t = data.map { it -> it.getOrElse(index) { 0.0 } }
        result.add(t.sum())
    }
    return result
}
o
Try
sumBy
instead of mapping and then summing
also
maxBy
for the
longest
a
sumBy certainly cleaned up some noise 👍