Swift running sum

前端 未结 7 995
一生所求
一生所求 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:16

    Just for fun: The running sum as a one-liner:

    let arr = [1, 2, 3, 4]
    
    let rs = arr.map({ () -> (Int) -> Int in var s = 0; return { (s += $0, s).1 } }())
    
    print(rs) // [1, 3, 6, 10]
    

    It does the same as the (updated) code in JAL's answer, in particular, no intermediate arrays are generated. The sum variable is captured in an immediately-evaluated closure returning the transformation.

    0 讨论(0)
提交回复
热议问题