I am trying to create an array from this following array arr=[1,2,3,4,5,6,7,8,9] and it will return as sum of numbers in this way 1 3 =4 ,3 5=8,5 7=12,7 9=16. so that final answer would be newArray =[4,8,12,16]. How can I achieve it. I have done below code but it doesn't work .
fun main(){
val sum = arrayOf(1,2,3,4,5,6,7,8,9)
var first =0;
var second=0
for (i in sum.indices){
if(sum[i]%2!=0){
first = sum[i]
if (second!=0){
println(" $first $second")
first=second
}
}
}
}
CodePudding user response:
// val arr = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
val arr = arrayOf(1, 3, 5, 6, 7, 8, 2, 4, 9) // shuffled for test purposes
val result = arr
// I first posted this line, which was wrong:
// .filterIndexed { index, _ -> index % 2 == 0 }
.filterIndexed { _, value -> value % 2 == 1 }
.windowed(2, 1)
.map { it.sum() }
println(result)
Details of the three steps:
- After filterIndexed: [1, 3, 5, 7, 9]
- After windowed: [[1, 3], [3, 5], [5, 7], [7, 9]]
- And in the map each sublist is summed up.
Edit: The first version of this answer with filtering for index % 2 == 0 does by coincidence lead to the same result, because the input array in the OP was not shuffled.
CodePudding user response:
lukas.j's answer is superior, but I wanted to also show a solution with only slight changes to your own code:
val sum = arrayOf(1,2,3,4,5,6,7,8,9)
var first =0;
var second=0
var result = emptyArray<Int>()
for (i in sum.indices){
if(sum[i]%2!=0){
if (first == 0) first = sum[i]
else second = sum[i]
if (second!=0){
println(" $first $second")
result = first second
first=second
}
}
}
println(result.contentToString())