0

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!

3 Answers 3

5

May be this:

var arr = [8, 9, 8]

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

print(arr)
Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm. Thank you.
2

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]

1 Comment

@Alexander yea, as I said, there are better solutions than this one
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.