I'm currently practicing on hackerrank and came across a challenge involving a two-dimensional matrix. Unfortunately, I encountered an error in my code implementation.
- 11 2 4
- 4 5 6
- 10 8 -12
The task at hand is to calculate the sum along the primary diagonal: 11 + 5 - 12 = 4, then the secondary diagonal: 4 + 5 + 10 = 19, finally resulting in 19 - 4 = 15.
function diagonalDifference(arr) {
var sumRight = 0;
var sumLeft = 0;
var array = new Array();
for(var i = 0; i < arr.length ; i++ ){
for(var j = 0; j < arr[i].length; j++){
array.push(arr[i][j]);
}
}
for (var i = 0 ; i < array.length; i = i + 4){
sumRight += array[i];
}
for (var j = 2 ; j < array.length - 1 ; j = j + 2 ){
sumLeft += array[j];
}
return sumLeft - sumRight;
}