[HackerRank - Java] Day 2 - 2. Diagonal Difference

2023. 1. 27. 14:47Java/coding test

반응형

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 1+5+9=151 + 5 + 9 = 15. The right to left diagonal 3+5+9=173 + 5 + 9 = 17. Their absolute difference is 1517=2|15 - 17| = 2.

Function description

Complete the diagonalDifferencediagonalDifference 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, nn, the number of rows and columns in the square matrix arrarr.
Each of the next nn lines describes a row, arr[i]arr[i], and consists of nn space-separated integers arr[i][j]arr[i][j].

Constraints

  • 100<=arr[i][j]<=100-100 <= arr[i][j] <= 100

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


row와 col이 같은 행렬이 입력으로 주어질 때, 각 대각선의 합의 차를 구하는 코드를 작성하면 됩니다.

2중배열에서 배열 하나씩 읽으면서, cnt에 따라 앞에서 읽은 것은 primary에 합산하고 뒤에서 읽은 것은 secondary에 합산하면 됩니다.

static int diagonalDifference(List<List<Integer>> arr) {
    int primary = 0, secondary = 0;
    int cnt = 0, length = arr.size();
    for (List<Integer> a : arr) {
        primary += a.get(cnt);
        secondary += a.get(length - cnt - 1);
        cnt++;
    }
    return Math.abs(primary - secondary);
}
728x90
반응형