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 differenceInput 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
- Left to Right
- 이 경우 규칙성을 보면 arr[i][j]에서 i와 j가 같기때문에 해당 요소들의 합을 구했다.
- Right to Left
- arr[i][j]에서 i+j 값이 배열arr의 길이 -1 규칙을 찾아내어 구현했다.
- 절대값
- 1.과 2. 에서 나온값들을 토대로 차의 절대값을 구한다.
'Developer > Coding' 카테고리의 다른 글
[HackerRank] Staircase (1) | 2020.08.28 |
---|---|
[HackerRank] Plus Minus (0) | 2020.08.28 |
[HackerRank] A Very Big Sum (0) | 2020.08.28 |
[HackerRank] Compare the Triplets (0) | 2020.08.06 |
[HackerRank] Simple Array Sum (0) | 2020.08.06 |