How to check if a matrix columns contain numbers without repetition in Rust

1 Answer

0 votes
use std::collections::HashSet;

fn columns_have_unique_numbers(matrix: &[Vec<i32>]) -> bool {
    if matrix.is_empty() || matrix[0].is_empty() {
        return true;
    }

    let num_cols = matrix[0].len();
    for j in 0..num_cols {
        let mut column_set = HashSet::new();

        for row in matrix {
            if !column_set.insert(row[j]) {
                return false; // Duplicate found
            }
        }
    }
    true
}

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

    let matrix2 = vec![
        vec![1, 4, 7],
        vec![2, 4, 8],
        vec![3, 6, 9],
    ];

    println!("Matrix 1 columns have unique numbers: {}", columns_have_unique_numbers(&matrix1));
    println!("Matrix 2 columns have unique numbers: {}", columns_have_unique_numbers(&matrix2));
}


   
    
/*
run:
    
Matrix 1 columns have unique numbers: true
Matrix 2 columns have unique numbers: false
    
*/

 



answered May 28 by avibootz
...