티스토리 뷰
Question
Given a square matrix, calculate the absolute difference between the sums of its diagonals.
2d array 의 서로 다른 두 개의 대각선 값의 Absolute difference 즉, 절대값을 결과로 보여주는 문제.
For example,
1 2 3
4 5 6
9 8 9
(1 + 5 + 9) - (3 + 5+ 9)
|15 - 17|
the absolute difference is 2.
Tip.
0 1 2
0 o x o
1 x o x
2 o x o
필요한 부분이 나오는 배열의 형태를 먼저 적어주고 그 형태가 나올 수 있는 loop의 형태를 고민해 본다.
2d Array는 loop를 적용시키면 Column(세로) 이 순서대로 돌면서 각각의 row(가로) 를 순서대로 도는 형태를 띈다.
[column, row]
[0,0] [0,1] [0,2] 처음 loop 적용
[1,0] [1,1] [1,2] 두번째
[2,0] [2,1] [2,2] 세번째
대각선으로 계산되기에 필요한 부분은 아래와 같다.
first: [0,0] [1,1,] [2,2] -> 같은 수의 반복이니 loop에서 같은 수가 나오도록하는 loop를 고민
second: [0,2] [1,1] [2,0] -> 처음 수는 1씩 증가하는 형태 두번째는 2부터 1씩 줄어드는 형태. 2는 배열의 길이보다 1이 적음.
그래서 length도 필요해짐.
Absolute value(positive)를 return하는 내장함수 Math.abs 사용
Solution
let arr = [
[2, 1, 1],
[3, 2, 1],
[1, 6, 2]
];
function diagonalDifference(arr) {
let sum1 = 0, sum2 = 0;
let leng = arr.length;
for( let i = 0; i < arr.length; i++){
sum1 += arr[i][i];
sum2 += arr[i][leng - 1 - i]
}
return Math.abs(sum1 - sum2);
}
const result = diagonalDifference(arr);
console.log(result); //2
Reference
https://www.hackerrank.com/challenges/diagonal-difference/problem
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/abs
'Algorithms' 카테고리의 다른 글
Staircase (0) | 2020.08.04 |
---|---|
Plus Minus (0) | 2020.07.29 |
Calculate the Max minus Min Value in Array (0) | 2019.09.08 |
Get the second smallest element in array (0) | 2019.09.07 |
Counting Valley (0) | 2019.08.31 |
- Total
- Today
- Yesterday
- 프로그래머스
- Object type casting
- spring boot application
- rest parameter
- hackerrank
- easy algorithm
- substring()
- hackerrank javascript
- math.abs
- C++
- javascript
- algorithm
- Collection Framework
- ... in Javascript
- 알고리즘
- java
- math.max
- easy javascript algorithm
- code refactoring
- hackerrank javascript solution
- 프로그래머스 알고리즘문제
- compareTo()
- equals()
- Javascript Algorithm
- HashMap
- hackerrank solution
- 프로그래머스 알고리즘
- string class in java
- HackerRank Algorithm
- repeat()
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |