How to sum the corners of a matrix in Rust

2 Answers

0 votes
// 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 {
    // Return 0 for an empty matrix.
    if matrix.is_empty() || matrix[0].is_empty() {
        return 0;
    }

    let rows = matrix.len();
    let cols = matrix[0].len();

    // Add the four corner elements.
    matrix[0][0]
        + matrix[0][cols - 1]
        + matrix[rows - 1][0]
        + matrix[rows - 1][cols - 1]
}

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

*/

 



answered Oct 11 by avibootz
0 votes
// 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

*/

 



answered Oct 11 by avibootz
...