David Robertson
David Robertson

Reputation: 1581

Sum progression in an array Swift

I have an basic Int array

Array = [8, 9, 8]

How do i sum all of its values progressively so that the end result would look like this

EndResult = [8, 17, 25]

Tried using for and while loops, but to no avail.

NB: Basic array[0] + array[1] advices will not work. I'm looking for something automatic like a loop solution.

Looking forward to your advices.

Thanks!

Upvotes: 0

Views: 1476

Answers (3)

Charles A.
Charles A.

Reputation: 11143

You could use a reduce function in Swift to accomplish this. Note that you can't really do it with map, because you would need to know what the previous call to the map function returned, keep state in a variable outside the map function (which seems dirty), or loop over your array for every map function call.

    let array = [8, 9, 8]
    let results = array.reduce((0, []), combine: { (reduction: (lastValue: Int, values: Array<Int>), value: Int) in
        let newValue = reduction.lastValue + value
        return (newValue, reduction.values + [newValue])
    }).1

Upvotes: 1

Daniel Krom
Daniel Krom

Reputation: 10068

Probably there are better ways than this one, but it works

var array = [8, 9, 8]
var result = [Int]()
for i in 0..<array.count{
    var temp = 0;
    for j in 0...i{
        temp+=array[j]
    }
    result.append(temp)
}
print(result) //[8, 17, 25]

Upvotes: 2

Alexander
Alexander

Reputation: 2297

May be this:

var arr = [8, 9, 8]

for i in 1..<arr.count {
    arr[i] += arr[i-1]
}

print(arr)

Upvotes: 5

Related Questions