How to find repeated rows of a matrix in Rust

1 Answer

0 votes
use std::collections::HashMap;

fn row_to_string(row: &[i32]) -> String {
    row.iter().map(|num| num.to_string()).collect::<Vec<String>>().join(",")
}

fn find_repeated_rows(matrix: &[Vec<i32>]) {
    let mut row_count: HashMap<String, i32> = HashMap::new();

    for row in matrix {
        let pattern = row_to_string(row);
        *row_count.entry(pattern).or_insert(0) += 1;
    }

    println!("Repeated Rows:");
    for (pattern, count) in &row_count {
        if *count > 1 {
            println!("Row: [{}] - Repeated {} times", pattern, count);
        }
    }
}

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

    find_repeated_rows(&matrix);
}

  
   
/*
run:
   
Repeated Rows:
Row: [1,2,3] - Repeated 2 times
Row: [4,5,6] - Repeated 3 times
   
*/

 

 



answered May 24 by avibootz
...