Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

225
Visualizações
How to return multiple elements from collection?

In the list I need to replace each element with the sum of this element and all previous ones. The first element is not required to change. Example: The list (1.0, 2.0, 3.0, 4.0) must be converted (1.0, 3.0, 6.0, 10.0). I'm looking for the most concise and correct way.

I was googling for a long time and could not find any useful information regarding the conversion of an element by the sum of its previous ones. Also I could not find the required function in the standard library at Kotlinlang.org. Please help solve this 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
}
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You have to use a variable that stores the running sum.

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 for this code.

If you'd prefer to do it the FP way and non-destructively transform the list, you can write this:

fun accumulate(list: List<Double>): List<Double> {
    var runningSum = 0.0
    return list.map {
        runningSum += it
        runningSum
    }
}
over 4 years ago · Santiago Trujillo Relatório

0

You can write this simpler, by using slice() and sum():

fun accumulate(list: MutableList<Double>) = list.mapIndexed { index, d -> list.slice(0..index).sum() }.toMutableList()
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda