JavaScript Coding Challenge #6

If you love arrays as much as I do, this post is for you! :smiley:

Feedback is highly appreciated! :slight_smile:

2 Likes

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);
}
1 Like

Perfect @ksjazzguitar! That is indeed faster! :wink:

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 :stuck_out_tongue:

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);
}
2 Likes

Very nice! :smiley: You are very good at this! :wink: