Oh and Hackerrank…

I was talking the other day about online learning resources which I use, and despite the fact I kept it brief, upon a session today tidying up some bookmarks I had and was aghast to realise that I had forgotten about HackerRank!

So what is HackerRank and why is it awesome? It is reasonably similar to CheckIO which I mentioned, in that there are a bunch of challenges. They work slightly differently through as the challenges are (often) not language specific, they merely provide a data input, and test for a data output. The language you use in between is up to you.

HackerRank user profile dashboard

Plus, you get badges. Who doesn’t like badges!?

Sample Challenges

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

For example, the square matrix  is shown below:

1 2 3
4 5 6
9 8 9  

The left-to-right diagonal = . The right to left diagonal = . Their absolute difference is .

Function description

Complete the  function in the editor below. It must return an integer representing the absolute diagonal difference.

diagonalDifference takes the following parameter:

  • arr: an array of integers .

Input Format

The first line contains a single integer, , the number of rows and columns in the matrix . 
Each of the next  lines describes a row, , and consists of  space-separated integers .

Constraints

  • -100 <= arr[i][j] <= 100

Output Format

Print the absolute difference between the sums of the matrix’s two diagonals as a single integer.

Sample Input

3
11 2 4
4 5 6
10 8 -12

Sample Output

15

Explanation

The primary diagonal is:

11
   5
     -12

Sum across the primary diagonal: 11 + 5 – 12 = 4

The secondary diagonal is:

     4
   5
10

Sum across the secondary diagonal: 4 + 5 + 10 = 19 
Difference: |4 – 19| = 15

Note: |x| is the absolute value of x

(My) Solution:
N.B. The input is parsed into a function as ‘arr’.

function diagonalDifference(arr) {

var n = arr.length;
var diagA = 0;
var diagB = 0;
var total = 0;

// To get diagonals
for (var i = 0; i < arr.length; i++) {
diagA += arr[i][i];

// Taking the end value <-- Made my brain hurt
diagB += arr[i][n-1-i];
}

total = Math.abs(diagA - diagB);
return total;

}

IMHO, my solution is elegantly simple, with elements of sheer genius…

Leave a Reply

Your email address will not be published. Required fields are marked *