In Kotlin I have two lists:
val x: List<Int> = listOf(1,2,3,4,5,6)
val y: List<Int> = listOf(2,3,4,5,6,7)
How do I get:
val z: List<Int> = 3,5,7,9,11,13
without using loops?
Assuming both list have the same size:
Using zip
val sum = x.zip(y) { xv, yv -> xv + yv }
Using simple map
and mapIndexed
val sum = (0 until x.size).map { x[it] + y[it] }
// or
val sum = x.mapIndexed { index, xv -> xv + y[index] }
When the size can be different and you would assume 0 for out of range entries:
Using an array
val sum = IntArray(maxOf(x.size, y.size)) {
x.getOrElse(it, {0}) + y.getOrElse(it, {0})
}.toList()
Using range:
val sum = (0 until maxOf(x.size, y.size)).map {
x.getOrElse(it, {0}) + y.getOrElse(it, {0})
}
Extending the lists to same size
val xExtended = x + Array(maxOf(0, y.size - x.size), { 0 })
val yExtended = y + Array(maxOf(0, x.size - y.size), { 0 })
val sum = xExtended.zip(yExtended) { xv, yv -> xv + yv }
I'd go with a range and map
:
val sums = (0 until x.size).map { x[it] + y[it] }
It's probably less overhead than zip
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With