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?