# 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
# Returns the sum of unique corner elements.
def sum_corners(matrix)
return 0 if matrix.empty? || matrix[0].empty?
rows = matrix.length
cols = matrix[0].length
corners = [
[0, 0],
[0, cols - 1],
[rows - 1, 0],
[rows - 1, cols - 1]
]
corners.uniq.sum { |r, c| matrix[r][c] }
end
# Example usage
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
puts "Sum of corners: #{sum_corners(matrix)}"
# run:
#
# Sum of corners: 26
#