Java – how do I return multiple elements from a collection?

In the list, I need to replace each element with the sum of this element and all previous elements The first element does not need to be changed

I searched Google for a long time and couldn't find any useful information about element conversion Besides, I'm in kotlinlang The required function cannot be found in the standard library of org Please help solve the problem

fun accumulate(list: MutableList<Double>): MutableList<Double> {
    if (list.isEmpty()) return list
    else for (i in 0 until list.size) {
        if (i == list.indexOf(list.first())) list[i] = list.first()
        else list[i] = list.sumByDouble { it } // here's my problem
    }
    return list
}

Solution

You must use a variable that stores the sum of runs

fun accumulate(list: MutableList<Double>): MutableList<Double> {
    var runningSum = 0.0
    list.indices.forEach { i ->
        runningSum += list[i]
        list[i] = runningSum
    }
    return list
}

Note that an empty list is not a special case of this code

If you prefer FP mode and convert the list non destructively, you can write as follows:

fun accumulate(list: List<Double>): List<Double> {
    var runningSum = 0.0
    return list.map {
        runningSum += it
        runningSum
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>