How to check whether a matrix is a magic square or not in Rust

1 Answer

0 votes
fn is_magic_square(matrix: &[Vec<i32>]) -> bool {
    let size = matrix.len();
    let mut sum_diagonal1 = 0;
    let mut sum_diagonal2 = 0;

    // Calculate the sum of the primary diagonal
    for i in 0..size {
        sum_diagonal1 += matrix[i][i];
    }

    // Calculate the sum of the secondary diagonal
    for i in 0..size {
        sum_diagonal2 += matrix[i][size - i - 1];
    }

    // If the two diagonals don't have the same sum, it's not a magic square
    if sum_diagonal1 != sum_diagonal2 {
        return false;
    }

    // Check sums of each row and column
    for i in 0..size {
        let mut sum_row = 0;
        let mut sum_col = 0;

        for j in 0..size {
            sum_row += matrix[i][j];  // Sum of the current row
            sum_col += matrix[j][i];  // Sum of the current column
        }

        // If any row or column sum is not equal to the diagonal sum, it's not a magic square
        if sum_row != sum_diagonal1 || sum_col != sum_diagonal1 {
            return false;
        }
    }

    // If all checks pass, it's a magic square
    true
}

fn main() {
    let matrix = vec![
        vec![8, 3, 4],
        vec![1, 5, 9],
        vec![6, 7, 2],
    ];

    // Check if the matrix is a magic square
    if is_magic_square(&matrix) {
        println!("The given matrix is a magic square.");
    } else {
        println!("The given matrix is NOT a magic square.");
    }
}


/*
run:

The given matrix is a magic square.

*/

 



answered Sep 30 by avibootz
...