How to sum the corners of a matrix in Swift

2 Answers

0 votes
import Foundation

/// Returns the sum of the corner elements of a matrix.
///
/// Example:
/// 1  2  3  4
/// 5  6  7  8
/// 9 10 11 12
///
/// Corners:
/// - 1  (top-left)
/// - 4  (top-right)
/// - 9  (bottom-left)
/// - 12 (bottom-right)
///
/// Sum = 26
///
/// This implementation counts each corner only once, making it
/// safe for:
/// - 1×1 matrices
/// - 1×N matrices
/// - N×1 matrices
///
/// - Parameter matrix: A rectangular matrix of integers.
/// - Returns: The sum of the unique corner elements.
func sumCorners(of matrix: [[Int]]) -> Int {
    // Ensure the matrix is not empty.
    guard !matrix.isEmpty, !matrix[0].isEmpty else {
        return 0
    }

    let rowCount = matrix.count
    let columnCount = matrix[0].count

    // Store unique corner coordinates.
    let corners: Set<[Int]> = [
        [0, 0],                           // Top-left
        [0, columnCount - 1],             // Top-right
        [rowCount - 1, 0],                // Bottom-left
        [rowCount - 1, columnCount - 1]   // Bottom-right
    ]

    // Sum the values at each unique corner.
    return corners.reduce(0) { sum, corner in
        sum + matrix[corner[0]][corner[1]]
    }
}

// Example usage
let matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
]

print("Sum of corners: \(sumCorners(of: matrix))")


/*
run:

Sum of corners: 26

*/

 



answered Oct 11 by avibootz
0 votes
import Foundation

/// Returns the sum of the corner elements of a matrix.
///
/// Example:
/// 1  2  3  4
/// 5  6  7  8
/// 9 10 11 12
///
/// Corners:
/// - 1  (top-left)
/// - 4  (top-right)
/// - 9  (bottom-left)
/// - 12 (bottom-right)
///
/// Sum = 26
///
/// This implementation counts each corner only once, making it
/// safe for:
/// - 1×1 matrices
/// - 1×N matrices
/// - N×1 matrices
///
/// - Parameter matrix: A rectangular matrix of integers.
/// - Returns: The sum of the unique corner elements.
/// Returns the sum of the four corner elements.
func sumCorners(of matrix: [[Int]]) -> Int {
    guard !matrix.isEmpty, !matrix[0].isEmpty else {
        return 0
    }

    let lastRow = matrix.count - 1
    let lastColumn = matrix[0].count - 1

    return matrix[0][0]
         + matrix[0][lastColumn]
         + matrix[lastRow][0]
         + matrix[lastRow][lastColumn]
}

// Example usage
let matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
]

print("Sum of corners: \(sumCorners(of: matrix))")


/*
run:

Sum of corners: 26

*/

 



answered Oct 11 by avibootz
...