Skip to content

Instantly share code, notes, and snippets.

@petercr
Created February 23, 2022 23:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petercr/1e711bfa33bf733daca661dbb325ae3e to your computer and use it in GitHub Desktop.
Save petercr/1e711bfa33bf733daca661dbb325ae3e to your computer and use it in GitHub Desktop.
A JavaScript function takes in a 2D array and adds the diagonal values each way. It then compares the absolute value of both.
/*
* Complete the 'diagonalDifference' function below.
*
* The function is expected to return an INTEGER.
* The function accepts 2D_INTEGER_ARRAY arr as parameter.
*
*/
function diagonalDifference(arr) {
// Loop over the array both ways
// Add the values to each result
// Return the absolute value of the final result
let forwardResult = 0;
let backwardResult = 0;
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
if (i === j) {
forwardResult += arr[i][j];
}
if (i + j === arr.length - 1) {
backwardResult += arr[i][j];
}
}
}
const finalResult = Math.abs(forwardResult - backwardResult);
return finalResult;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment