JavaScript solution for diagonal difference 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 &lt;= numberOfInputs ; currentLine++)
        {
            var inputs = inputAll[currentLine];
            var inputArray = inputs.split(" ");


            for(var i=0 ; i&lt;=(numberOfInputs-1);i++)
                {
                    if(i == (currentLine - 1))
                        {

                            sumFirstDiagonal = sumFirstDiagonal + parseInt(inputArray[i]);
                        }
                }

            for(var j=(numberOfInputs-1) ; j&gt;=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");
}
You don't need the inner for loops because you know exactly which array element you want for each sum:

for(currentLine = 1 ; currentLine &lt;= numberOfInputs ; currentLine++)
    {
        var inputs = inputAll[currentLine];
        var inputArray = inputs.split(" ");

        sumFirstDiagonal += parseInt( inputArray[ currentLine - 1 ])
        sumSecondDiagonal += parseInt (inputArray [ inputArray.length - currentLine ])

    }