hackerrank.com - diagonal difference:
Problem Statement
You are given a square matrix of size N×N. Calculate the absolute difference of the sums across the two main diagonals.
Input Format
The first line contains a single integer N. The next N lines contain N integers (each) describing the matrix.
Constraints
- \$1 \le N \le 100\$
- \$−100 \le A[i] \le 100\$
Output Format
Output a single integer equal to the absolute difference in the sums across the diagonals.
Sample Input
3 11 2 4 4 5 6 10 8 -12
Sample Output
15
Explanation
The first diagonal of the matrix is:
11 5 -12
Sum across the first diagonal = 11+5-12= 4
The second diagonal of the matrix is:
4 5 10
Sum across the second diagonal = 4+5+10 = 19
Difference: |4-19| =15
How can this solution be improved?
function processData(input) {
inputAll = input.split("\n");
var currentLine = 0;
var numberOfInputs = parseInt(inputAll[currentLine].trim(), 10);
currentLine = 1;
var sumFirstDiagonal = 0;
var sumSecondDiagonal = 0;
var difference = 0;
for(currentLine = 1 ; currentLine <= numberOfInputs ; currentLine++)
{
var inputs = inputAll[currentLine];
var inputArray = inputs.split(" ");
for(var i=0 ; i<=(numberOfInputs-1);i++)
{
if(i == (currentLine - 1))
{
sumFirstDiagonal = sumFirstDiagonal + parseInt(inputArray[i]);
}
}
for(var j=(numberOfInputs-1) ; j>=0;j--)
{
if(j == ( (numberOfInputs - 1) - (currentLine - 1)))
{
sumSecondDiagonal = sumSecondDiagonal + parseInt(inputArray[j]);
}
}
}
difference = sumFirstDiagonal - sumSecondDiagonal;
difference = Math.abs(difference);
process.stdout.write(""+difference+"\n");
}