Problem Description:
Given a square matrix, calculate the absolute difference between the sums of its diagonals:
- Primary Diagonal: Runs from the top-left corner to the bottom-right corner.
- Secondary Diagonal: Runs from the top-right corner to the bottom-left corner.
Mathematical Expression: If matrix[i][j] represents the element at the i-th row and j-th column:
- Primary diagonal elements: matrix[i][i] where i=0,1,2,…,n−1
- Secondary diagonal elements: matrix[i][n−i−1] where i=0,1,2,…,n−1
Goal: Compute:
Diagonal Difference = | Sum of Primary Diagonal−Sum of Secondary Diagonal |
Example
Input:
11 | 2 | 4 |
4 | 5 | 6 |
10 | 8 | -12 |
Calculations:
- Primary Diagonal: 11+5+(−12) = 4
- Secondary Diagonal: 4+5+10=19
- Absolute Difference: ∣4−19∣ = 15
Output: 15
Kotlin Solution
Below is a Kotlin implementation to calculate the diagonal difference:
Kotlin
fun diagonalDifference(matrix: Array<Array<Int>>): Int {
val n = matrix.size
var primaryDiagonalSum = 0
var secondaryDiagonalSum = 0
for (i in 0 until n) {
primaryDiagonalSum += matrix[i][i] // Add primary diagonal element
secondaryDiagonalSum += matrix[i][n - i - 1] // Add secondary diagonal element
}
return kotlin.math.abs(primaryDiagonalSum - secondaryDiagonalSum)
}
fun main() {
// Example matrix
val matrix = arrayOf(
arrayOf(11, 2, 4),
arrayOf(4, 5, 6),
arrayOf(10, 8, -12)
)
val result = diagonalDifference(matrix)
println("Diagonal Difference: $result") // Output: 15
}
Explanation of the Code
- Input Matrix:
- The matrix is represented as a 2D array of integers.
- Diagonal Sums:
- A
for
loop iterates through each row of the matrix (0
ton-1
). - Add the element at
[i][i]
for the primary diagonal. - Add the element at
[i][n-i-1]
for the secondary diagonal.
- A
- Absolute Difference:
- The absolute difference is computed using
kotlin.math.abs()
.
- The absolute difference is computed using
- Main Function:
- An example matrix is tested to demonstrate the implementation.
Complexity Analysis
- Time Complexity: O(n)O(n)O(n), where nnn is the number of rows/columns in the square matrix. The algorithm makes a single pass through the rows.
- Space Complexity: O(1)O(1)O(1), as only a few variables are used to store intermediate sums.
This approach efficiently calculates the diagonal difference for any square matrix.