0

Assume I have an existing IntArray: values = [1,2,3,4,5]. Now I need to create another array which holds the sum of all numbers in the original array up to the current index. For example:

sum = [1,3,6,10,15] 

because

sum[0] = values[0] (= 1)
sum[1] = values[0] + values[1] (= 1 + 2 = 3)
...

Currently I create sum by:

val sum = IntArray(values.size) {0}
sum[0] = values[0]
for(index in 1 until sum.size) {
  sum[index] = sum[index-1] + values[index]
}

Problem with this code is it needs to provide the initial value of 0 just to create the array. I feel it is quite redundant.

I understand that Kotlin allows a lambda to be pass to an array's constructor. However code like below wouldn't compile because it references sum while sum hasn't been initialised.

val sum = IntArray(values.size) { index ->
   if(index == 0) values[index]
   else sum[index-1] + values[index]
}

I was wondering if there is any nicer way of doing this?

1 Answer 1

1

You can use map function for that:

val values = arrayOf(1,2,3,4,5)

var sum = 0
val sumList = values.map {
    sum += it
    sum
}

Or more concise way is to use scanReduce function:

val values = arrayOf(1,2,3,4,5)
val sumList = values.scanReduce { acc, v ->
    acc + v
}

Note: at the time of writing, scanReduce function is an experimental, so all functions in call hierarchy should be marked with @ExperimentalStdlibApi annotation.

If you need exactly IntArray type:

val sumArray = sumList.toIntArray()
Sign up to request clarification or add additional context in comments.

2 Comments

map returns List<Int>, val sumArray = IntArray(values.size) { sum+=values[it]; sum }
Thanks for your answer. It's a great use of map and scanReduce but I would want to avoid transforming back and forth between array and list. So I guess @IR42's comment makes more sense for this scenario.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.