-3

Here is my array:

array = [100.0, 10.0, 250.0, 360.0]

The final number is the total and works well with what I want, however, what I'm really looking for is this:

array = [100.0, 110.0, 360.0]

In more words I want the starting value to stay the same and then each additional value to be the sum of the value before + the next value...

Any help would be awesome. I started writing a for statement, but I dont know how to raise the index for each statement? I think its something like i++?

Thank you

Hamish
  • 78,605
  • 19
  • 187
  • 280
Denis
  • 570
  • 9
  • 23
  • [Edit] your question with your code. Show what you have tried. Explain what issues you are having. – rmaddy Mar 24 '17 at 16:33

4 Answers4

1

You can accomplish this by using a var total to keep track of the running total and use map to create a new array with each item replaced by total of it and the previous ones:

let array = [100.0, 10.0, 250.0]
var total = 0.0

let result = array.map { value -> Double in total += value; return total }
print(result)
[100.0, 110.0, 360.0]

Using a for loop:

This accomplishes the same task using a for loop to build up the result:

let array = [100.0, 10.0, 250.0]
var result = [Double]()
var total = 0.0

for value in array {
    total += value
    result.append(total)
}

print(result)
[100.0, 110.0, 360.0]
vacawama
  • 150,663
  • 30
  • 266
  • 294
1

The easiest and most straightforward way is by using a for loop.

let numbers = [100.0,10.0,250.0]

var sum = [Double]()

for number in numbers{
    sum.append((sum.last ?? 0.0) + number)
}    
// sum : [100.0, 110.0, 360.0]
0

You are looking for a running sum:

let array = [100.0, 10.0, 250.0]
let runningSum = array.reduce([Double]()) { aggregate, element in
    aggregate + [aggregate.last ?? 0 + element]
}

print(runningSum)
Mike Henderson
  • 2,028
  • 1
  • 13
  • 32
-1

You don't show how you add these values to the array so I can't give you a complete answer. Where you add the new value do:

array.append(array.last + newValue)

This adds a value to the array that is the last value + a new value. This does require the array to be ordered.

Edit: I cannot remember now if you can call .last when appending, if you can't you can get arround that doing:

let last = array.last
array.append(last + newValue)
Casper Zandbergen
  • 3,419
  • 2
  • 25
  • 49