Given a multidimensional array, find the recursive alternating sum. An alternating sum is simply the sum of an array, where every other item (starting with the second) is negated. For example, the alternating sum of [7, 1, 6, -4, -2]
is the sum of [7, -1, 6, 4, -2]
, or 14
. In this challenge, you'll take the alternating sum of a multidimensional array.
Task:
Given an array like this:
[
[
[1, 2], [2, 4], [4, 8]
],
[
[-4, -4], [-1, 1], [2, -2]
]
]
First find the alternating sums of all of the deepest nested arrays:
[
[-1, -2, -4],
[0, -2, 4]
]
Then do this again:
[-3, 6]
And finally:
-9
You can choose how input is represented, but it must be able to handle multidimensional arrays of any number of dimensions possible in the language you use. You don't need to support ragged arrays.
Test cases:
[1] 1
[-1] -1
[1, 2] -1
[2, 0, 4] 6
[1, -2] 3
[[1]] 1
[[1, 2], [4, 8]] 3
[[-1, -1], [2, 2]] 0
[[[[1], [2]], [[4], [8]]]] 3
[[[1, 2], [2, 4], [4, 8]], [[-4, -4], [-1, 1], [2, -2]]] -9
Other:
This is code-golf, so shortest answer (per language) wins!