Swift running sum

前端 未结 7 1016
一生所求
一生所求 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 18:56

    Assuming an array of Ints, sounds like you can use map to manipulate the input:

    let arr = [0,1,0,1,0,1]
    
    var sum = 0
    let val = arr.map { (sum += $0, sum).1 }
    
    print(val) // "[0, 1, 1, 2, 2, 3]\n"
    

    I'll keep working on a solution that doesn't use an external variable.

提交回复
热议问题