티스토리 뷰

 

 

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

 

Diagonal Difference | HackerRank

Calculate the absolute difference of sums across the two diagonals of a square matrix.

www.hackerrank.com

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/abs

 

Math.abs()

The Math.abs() function returns the absolute value of a number

developer.mozilla.org

 

'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