Member-only story
In today’s algorithm, we will be creating a function called diagonalDifference. For this function you will receive an input that is a multi-dimensional array. A multi-dimensional array is an array containing arrays.
An in this function you will calculate and return the absolute difference between the sums of its diagonals.
If you look at the post image above, think of the input array as a tic tac toe grid. Each item in the array will contain an array of three values. Each row, you calculate the blue and pink circles in that row. In other words, in the example array:
[[1,2,3], [4,5,6], [7,8,9]]
You can also arrange the array to be easier to read and resemble a tic tac toe grid:
[
[1,2,3],
[4,5,6],
[7,8,9]
]
The diagonal going from left-to-right would be 1,5 and 9. The diagonal going right-to-left would be 3, 5, 7. The end goal is to take the sum of the left-to-right diagonal and subtract it from the sum of the right-to-left diagonal. Remember, you return the absolute difference so if the total becomes a negative number, you get the absolute value of that number and return the result.
Let’s turn this into code.
We create a series of variables:
let forwardIndex = 0;
let backwardsIndex = arr.length - 1;