How to sum the corners of a matrix in Kotlin

1 Answer

0 votes
/**
 * Returns the sum of the corner elements of a matrix.
 *
 * Examples:
 *
 * 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 position only once,
 * so it correctly handles:
 * - 1x1 matrices
 * - 1xN matrices
 * - Nx1 matrices
 *
 * @param matrix A rectangular matrix represented as a list of lists.
 * @return The sum of the unique corner elements.
 * @throws IllegalArgumentException if the matrix is empty.
 */
fun sumCorners(matrix: List<List<Int>>): Int {
    require(matrix.isNotEmpty()) { "Matrix must not be empty." }
    require(matrix[0].isNotEmpty()) { "Matrix rows must not be empty." }

    val rowCount = matrix.size
    val columnCount = matrix[0].size

    // Store corner coordinates.
    val corners = setOf(
        0 to 0,                             // Top-left
        0 to (columnCount - 1),             // Top-right
        (rowCount - 1) to 0,                // Bottom-left
        (rowCount - 1) to (columnCount - 1) // Bottom-right
    )

    // Sum the values at the unique corner positions.
    return corners.sumOf { (row, col) ->
        matrix[row][col]
    }
}

fun main() {
    val matrix = listOf(
        listOf(1, 2, 3, 4),
        listOf(5, 6, 7, 8),
        listOf(9, 10, 11, 12)
    )

    println("Sum of corners: ${sumCorners(matrix)}")
}



/*
run:

Sum of corners: 26

*/

 



answered Oct 11 by avibootz
...