샘성의 iOS 개발 일지

[Warm Up] Diagonal Difference 본문

Algorithm/HackerRank

[Warm Up] Diagonal Difference

SamusesApple 2023. 5. 11. 13:37
728x90

문제 설명:

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

 

Complete the  diagonalDifference 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  lines describes a row, arr[i], and consists of  space-separated integers arr[i][j].

 

Output Format

Return the absolute difference between the sums of the matrix's two diagonals as a single integer.

 

 

 

 

 

내 풀이:

func diagonalDifference(arr: [[Int]]) -> Int {
    var rightSideResult = 0
    var leftSideResult = 0

    guard let arrayCount = arr.last?.count else { return 0 }
    
    for i in 0...arrayCount-1 {
        // 0번째 배열의 0번째 index부터 arrayCount-1번째 배열의 arrayCount-1번째 index까지 더하기
        rightSideResult += arr[i][i]
        // 맨 밑의 배열의 0번째 index부터 거슬러 올라오면서 더해오기 
        leftSideResult += arr[arrayCount-1-i][i]
    }
    // 절대값 구하기
    return abs(leftSideResult - rightSideResult)
}

 

 

 

 

회고:

  처음에 abs()가 생각나지 않아 UInt()로 바꾼 후, 다시 Int()로 바꾸는 형식으로 풀었다. 역시나 50%의 정답률과 50%의 런타임 오류로 인해 탈락... 절대값 구하는 abs, 이번 기회에 잊지 말자

728x90

'Algorithm > HackerRank' 카테고리의 다른 글

[Implementation] Apple and Orange  (0) 2023.05.12
[Implementation] Grading Students  (0) 2023.05.12
[Warm Up] Time Conversion  (0) 2023.05.11
[Warm Up] Birthday Cake Candles  (0) 2023.05.11
[Warm Up] Staircase  (0) 2023.05.11