Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the sums for all elements of two lists in Kotlin?

Tags:

kotlin

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?

like image 224
PaulB Avatar asked Jan 24 '18 21:01

PaulB


2 Answers

Assuming both list have the same size:

  1. Using zip

    val sum = x.zip(y) { xv, yv -> xv + yv }
    
  2. 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:

  1. Using an array

    val sum = IntArray(maxOf(x.size, y.size)) { 
        x.getOrElse(it, {0}) + y.getOrElse(it, {0}) 
    }.toList()
    
  2. Using range:

    val sum = (0 until maxOf(x.size, y.size)).map { 
        x.getOrElse(it, {0}) + y.getOrElse(it, {0})
    }
    
  3. 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 }
    
like image 195
miensol Avatar answered Jan 01 '23 21:01

miensol


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.

like image 33
s1m0nw1 Avatar answered Jan 01 '23 22:01

s1m0nw1