[HackerRank] Diagonal Difference

Jayoung Lee·2020년 8월 28일
0

Diagonal Difference

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.
diagonalDifference takes the following parameter:
int arr[n][m]: an array of integers

Return

  • int: the absolute diagonal difference

Input Format

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

Constraints

Output Format

Return 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

function diagonalDifference(arr) {
    // Write your code here
    let ltr = 0; //left to right
    let rtl = 0; //right to left
    
    for(let i = 0; i < arr.length; i++){
        ltr += arr[i][i];
        rtl += arr[i][arr.length-i-1];
    }

    return Math.abs(ltr - rtl);
}

Result

  1. Left to Right
  • 이 경우 규칙성을 보면 arr[i][j]에서 i와 j가 같기때문에 해당 요소들의 합을 구했다.
  1. Right to Left
  • arr[i][j]에서 i+j 값이 배열arr의 길이 -1 규칙을 찾아내어 구현했다.
  1. 절대값
  • 1.과 2. 에서 나온값들을 토대로 차의 절대값을 구한다.

profile
프론트엔드 개발 공부하면서 아카이빙 중입니다 ʕ•ﻌ•ʔ

0개의 댓글