Created
February 23, 2022 23:18
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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