JavaScript Coding Challenge #6

Florin Pop
5 min readMar 13, 2017

--

Matrix. Today we’ll play a little bit with matrices! :D They are very useful in programming and I thought we must have a coding challenges that involves them.

As our last challenge, this one is also coming from HackerRank ^_^

Diagonal Difference

Given a square matrix of size n * n, calculate the absolute difference between the sums of its diagonals.

For those of you that aren’t so familiar with matrices, here is an example:

2  3  4
5 3 -1
9 8 -2

Which obviously gives us two diagonals: 2, 3, -2 and 4, 3, 9. If we add them up we’ll get a total of 3 for the first one and 16 for the second one. Their absolute difference is then equal to: |3 — 16| = 13. Simple as that :D.

We could also have a 4 * 4 matrix or even a 10 * 10 matrix, basically the sky is the limit!

The JavaScript solution

In JavaScript we’re going to have a matrix by combining multiple arrays into a bigger array. So the matrix from above will look like this in JavaScript: var matrix = [[2, 3, 4], [5, 3, -1], [9, 8, -2]], and we can manipulate each item as we would with an usual array. For example to get the first term we would write it like this: arr[0][0], as JavaScript arrays start with index 0. Pretty easy right? You’ll get used to it quickly :).

Ok… then our solution is kinda easy, right? Just note down all the indexes of the elements we need and then do the little math… How hard can it be?

Well… even though it might be ‘ok’ doing that manually with a 3 * 3 matrix, the approach is not a good idea in our case because we might get a different size matrix each time. In this case we need to calculate it more dynamically, using two loops.

One loop will iterate through each one of the rows (in the big array) and the other one will iterate through each element in the smaller arrays (or the inner arrays).

Suppose you have a function calculateDiagonals which will get a matrix as it’s input. Let’s first write those loops:

function calculateDiagonals(matrix){    var n = matrix.length;    for(var i=0; i<n; i++){        for(var j=0; j<n; j++){        }    }}

Note that I also saved the matrix.length into a variable n, which is used for our loops. This way we don’t need to recalculate the matrix length each iteration. This is a good way to save some computational time.

Great… so now we have two indexes: i and j which will increase on each iteration by one unit. Basically in a 2 * 2 matrix the indexes would look like this over each iteration:

i = 0 and j = 0;
i = 0 and j = 1;
i = 1 and j = 0;
i = 1 and j = 1;

For an matrix like: [[2, 3], [4, 0]] we’ll get step by step the following values: 2, 3, 4 and 0. Pretty neat!

Now that we know how to get each value out of the matrix, it’s time to focus on what we really need, the diagonals!

For a better learning experience, I’d suggest you take some time and figure out by yourself what is the relationship between the indexes (i and j) on each diagonal. I learned this by actually writing it on a piece of paper. Very useful!

Good! Now that you solved it, I’ll show you my approach and you can compare them! :D Here is a simple 3 * 3 matrix containing the indexes for both i and j:

(0, 0) (0, 1) (0, 2)
(1, 0) (1, 1) (1, 2)
(2, 0) (2, 1) (2, 2)

With i being the first number and j the second one.

The first diagonal

This one is pretty obvious. The main diagonal as it is called, contains those elements where the i index is equal to the j index.

The second diagonal

Or the counterdiagonal, it’s a little trickier. Let’s see what is the relationship.

As you might have noticed, if you add up the indexes on the second diagonal for this 3 * 3 matrix, you’ll always get a sum of 2. That’s the length of the matrix minus one. This will work for any given n * n matrix. Awesome right? :D

Now that we have this sorted out, let’s get back to our code.

I’m going to add two more variables which will store the sum of the elements of the diagonals, diag1 and diag2, and initialize them with 0:

function calculateDiagonals(matrix){    var n = matrix.length;
var diag1 = 0;
var diag2 = 0;
for(var i=0; i<n; i++){ for(var j=0; j<n; j++){ } }}

Next, let’s check if in the current iteration we have an element from either of the diagonals. If we do we’ll add them to the sum:

function calculateDiagonals(matrix){    var n = matrix.length;
var diag1 = 0;
var diag2 = 0;
for(var i=0; i<n; i++){ for(var j=0; j<n; j++){ // an element from the main diagonal
if(i === j) {
diag1 += matrix[i][j];
}
// an element from the second diagonal
if(i + j === n - 1){
diag2 += matrix[i][j];
}
} }}

Notice that I used two if statements, one for each diagonal. The first time I tried solving this problem I had an else statement for the second diagonal. But that is wrong, because when you have a matrix of n * n with n being an odd number, the center element will be on both diagonals and by using an else statement, it won’t get added up for the second diagonal total, in our case diad2 . I spent several minutes then figuring out where my bug was. :D

Perfect! All that’s left to do is to return the absolute difference of the diagonals:

function calculateDiagonals(matrix){    var n = matrix.length;
var diag1 = 0;
var diag2 = 0;
for(var i=0; i<n; i++){ for(var j=0; j<n; j++){ // an element from the main diagonal
if(i === j) {
diag1 += matrix[i][j];
}
// an element from the counterdiagonal
if(i + j === n - 1){
diag2 += matrix[i][j];
}
} } return Math.abs(diag1 - diag2);}

That’s all folks! Congratulations! :D

Conclusion

Arrays are fun and they are also very useful. JavaScript makes it very easy to play with them by offering a rich palette of helper functions. We’ll cover more of them in the future.

You can follow me to receive updates when I post new coding challenges. Also you could send me your solutions or your ideas for any coding challenge. I would be thrilled to read them. ;)

If you liked this challenge and you found it useful, I would sincerely appreciate a click on the Recommend button 💚.

P.S. Someone pointed out that there is a better way to solve the challenge. You can find a little follow up article here. Hope you’ll enjoy it! ^_^

--

--

Florin Pop

Dev Building In Public 💜 — YouTuber youtube.com/florinpop — Streamer twitch.tv/florinpop17 — eBook gum.co/makemoneydev 📕 — Journey $1M in 1000 Days 👇