// Returns the sum of the four corner elements of a matrix.
//
// For a matrix:
//
// 1 2 3 4
// 5 6 7 8
// 9 10 11 12
//
// The corners are:
// 1 (top-left)
// 4 (top-right)
// 9 (bottom-left)
// 12 (bottom-right)
//
// Sum = 1 + 4 + 9 + 12 = 26
fn sum_corners(matrix: &[Vec<i32>]) -> i32 {
if matrix.is_empty() || matrix[0].is_empty() {
return 0;
}
let rows = matrix.len();
let cols = matrix[0].len();
// Store unique corner coordinates.
let corners = [
(0, 0),
(0, cols - 1),
(rows - 1, 0),
(rows - 1, cols - 1),
];
let mut sum = 0;
for (i, &(r, c)) in corners.iter().enumerate() {
// Only add a corner if it hasn't already been counted.
if corners[..i].iter().all(|&(rr, cc)| rr != r || cc != c) {
sum += matrix[r][c];
}
}
sum
}
fn main() {
let matrix = vec![
vec![1, 2, 3, 4],
vec![5, 6, 7, 8],
vec![9, 10, 11, 12],
];
println!("Sum of corners: {}", sum_corners(&matrix));
}
/*
run:
Sum of corners: 26
*/