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 lists are the same size :
Using zip
zip
val sum = x.zip(y) { xv, yv -> xv + yv }
Using simple mapandmapIndexed
map
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 may differ and you would take 0 for entries out of range:
Using array
array
val sum = IntArray(maxOf(x.size, y.size)) { x.getOrElse(it, {0}) + y.getOrElse(it, {0}) }.toList()
Range Usage:
val sum = (0 until maxOf(x.size, y.size)).map { x.getOrElse(it, {0}) + y.getOrElse(it, {0}) }
Expanding 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 would go with a range and map:
val sums = (0 until x.size).map { x[it] + y[it] }
This is probably less overhead than zip.
Source: https://habr.com/ru/post/1692670/More articles:How to enable Rd warning "Missing file link" when creating packages in RStudio? - rCorrect error handling Rust (automatic conversion from one type of error to another with a question mark) - rustПитоновская обработка блока IF с двумя возможными значениями - pythonWeak links removed atomically with placement in the link queue? - javaR - customizable data table calendar function - rCalculate percentile rank for a given population - pythonPrint button print multiple pages - javascriptПочему экспорт/импорт свойств ES по умолчанию быстрее, чем свойства модуля имен? - javascriptThe attribute implementation for reference and non-reference types causes conflicting implementations - rustApollo refetch does not reindex a component - reactjsAll Articles