If you love arrays as much as I do, this post is for you!
Feedback is highly appreciated!
If you love arrays as much as I do, this post is for you!
Feedback is highly appreciated!
Did I miss something? Wouldnβt it be faster and easier with one loop?
function calculateDiagonals(matrix){
var n = matrix.length;
var diag1 = 0;
var diag2 = 0;
for(var i=0; i<n; i++){
diag1 += matrix[i][i];
diag2 += matrix[i][n-i-1];
}
return Math.abs(diag1 - diag2);
}
Thank you for the tip Kevin! Here is a little follow up on the sixth challenge:
Hope you donβt mind I used your solution
As I lay awake in bed last night, it also occurred to me that since (a1 + b1 + β¦) - (a2 + b2 + β¦) is the same as (a1 - a2) + (b1 - b2) + β¦ then we can save a further step by just summing the differences of the pairs instead of summing them individually and then taking their differences. Itβs a small time and memory saver, but it is a little better.
function calculateDiagonals(matrix){
var n = matrix.length;
var sumDiff = 0;
for(var i=0; i<n; i++){
sumDiff += matrix[i][i] - matrix[i][n-i-1];
}
return Math.abs(sumDiff);
}
Very nice! You are very good at this!