HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

JavaScript solution for diagonal difference

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
diagonaljavascriptdifferenceforsolution

Problem

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 =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");
}

Solution

You don't need the inner for loops because you know exactly which array element you want for each sum:

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

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

    }

Code Snippets

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

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

    }

Context

StackExchange Code Review Q#102106, answer score: 10

Revisions (0)

No revisions yet.