Monday, 24 February 2020

Diagonal Difference

Diagonal Difference


Objective

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

Description

For example, the square matrix  is shown below:
1   2   3
4   5   6
9   8   9
The left-to-right diagonal = 1 +  5 + 9 = 15. The right to left diagonal = 3 + 5 + 9 = 17. Their absolute difference is |15 - 17 | = 2

Code


Here’s my solution, with embedded comments:

function diagonalDifference(arr) {

    //here arr contains [[ 1,2,3 ] [ 4,5,6 ] [ 9,8,9 ]]

    //it means we have 3x3 metrics in the argument

    //depends on the input, we can also have nxn square matrics

    len = arr.length

    let diagonal1=0, diagonal2=0

    for( i=0 ; i<len ; i++){

        diagonal1 + = arr[i] [i]

        diagonal2 + = arr[len-1-i] [i]

    }

    total = Math.abs(diagonal1 - diagonal2)

    return total

}


I hope you found this helpful.
Cheers :)

No comments:

Post a Comment

Diagonal Difference

Diagonal Difference Objective Given a square matrix, calculate the absolute difference between the sums of its diagonals. Descripti...