Swift running sum

前端 未结 7 1030
一生所求
一生所求 2020-12-01 18:25

I\'d like a function runningSum on an array of numbers a (or any ordered collection of addable things) that returns an array of the same length where each eleme

7条回答
  •  无人及你
    2020-12-01 19:09

    One solution using reduce:

    func runningSum(array: [Int]) -> [Int] {
        return array.reduce([], combine: { (result: [Int], item: Int) -> [Int] in
            if result.isEmpty {
                return [item] //first item, just take the value
            }
    
            // otherwise take the previous value and append the new item
            return result + [result.last! + item]
        })
    }
    

提交回复
热议问题