📜  hackerrank 对角线差 (1)

📅  最后修改于: 2023-12-03 15:31:05.653000             🧑  作者: Mango

HackerRank - Diagonal Difference

HackerRank is a popular platform for programmers to practice their coding skills through a series of challenges and competitions. One of the challenges on the platform is the 'Diagonal Difference' problem, which tests a programmer's ability to work with matrices and manipulate their contents.

Problem Statement

Given a square matrix of size n x n, calculate the absolute difference between the sums of its diagonals. For example, the diagonal difference of the matrix below is |15 - 5| = 10:

1  2  3
4  5  6
9  8  9    
Approach

The problem requires the program to iterate through the elements of the matrix and calculate the sums of the two diagonals. The absolute difference between these sums then needs to be calculated and returned.

The following code snippet demonstrates the approach:

def diagonalDifference(arr):
    # Initialize variables
    left_sum = 0
    right_sum = 0
    n = len(arr)

    # Calculate sum of left diagonal
    for i in range(n):
        left_sum += arr[i][i]

    # Calculate sum of right diagonal
    for i in range(n):
        right_sum += arr[i][n - 1 - i]

    # Calculate absolute difference between the sums
    return abs(left_sum - right_sum)

The above code creates a function diagonalDifference that takes in a matrix arr and returns the absolute difference between the sums of its diagonals. The function first initializes variables for the left and right diagonal sums, as well as the size n of the matrix.

The function then iterates through the elements of the matrix and calculates the sums of the left and right diagonals using two separate for loops. Finally, it calculates the absolute difference between these sums using the abs function and returns the result.

Conclusion

The 'Diagonal Difference' problem on HackerRank is a great way for programmers to practice their matrix manipulation skills. By breaking down the problem into manageable steps, programmers can quickly and easily come up with an efficient solution that passes all test cases on the platform.