object MatrixCorners {
/**
* Returns the sum of the four corner elements of a matrix.
*
* Example matrix:
*
* 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 = 1 + 4 + 9 + 12 = 26
*/
def sumCorners(matrix: Array[Array[Int]]): Int = {
if (matrix.isEmpty || matrix(0).isEmpty) {
return 0
}
val rows = matrix.length
val cols = matrix(0).length
// Store the coordinates of the corners.
val corners = Set(
(0, 0),
(0, cols - 1),
(rows - 1, 0),
(rows - 1, cols - 1)
)
// Sum the values at the unique corner positions.
corners.map { case (r, c) => matrix(r)(c) }.sum
}
def main(args: Array[String]): Unit = {
val matrix = Array(
Array(1, 2, 3, 4),
Array(5, 6, 7, 8),
Array(9, 10, 11, 12)
)
println(s"Sum of corners: ${sumCorners(matrix)}")
}
}
/*
run:
Sum of corners: 26
*/