How do I calculate an array of differences?

3 Solutions Collect From Internet About “How do I calculate an array of differences?”

Sure, you can use map to do this fairly easily. You just have to keep track of the item before the current one.

Something like this should do the trick:

// your array
let arr = [1, 3, 6, 8]

// a variable to keep track of the previous item
var previousItem = 0
let arrOfDifferences:[Int] = arr.map {item in // the current item
    defer {previousItem = item} // set the previous item to the current one, after the return happens
    return item-previousItem // return the difference
}

print(arrOfDifferences) // [1, 2, 3, 2]

You can “zip” the array with a shift of itself and map the result
to the differences:

let numbers = [1,3,6,8]
let diffs = numbers.prefix(1) + zip(numbers, numbers.dropFirst()).map { $1 - $0 }
print(diffs) // [1, 2, 3, 2]

Explanation:

  • numbers.prefix(1) returns a sequence with the initial array
    element.
  • numbers.dropFirst() is a subsequence of all elements but the first,
    in this case 3, 6, 8.
  • zip(...) creates a sequence of pairs, stopping when the shorter
    input sequence is exhausted, in this case (1, 3), (3, 6), (6, 8).
  • map { $1 - $0 } maps this sequence of pairs to an array of the
    element-wise differences, in this case 2, 6, 3.

Here’s a solution using reduce:

[1,3,6,8].reduce(([], 0)) {
    ($0.0 + [$1 - $0.1], $1)
}.0 // [1,2,3,2]

Edit: here’s another solution with reduce that probably will perform better:

var differences = [Int]()
[1,3,6,8].reduce(0) {
    differences.append($1 - $0)
    return $1
}
// differences is now [1,2,3,2]