How to find repeated patterns of numbers in the rows of a matrix with Rust

1 Answer

0 votes
use std::collections::{HashMap, HashSet};

fn find_repeating_patterns(matrix: Vec<Vec<i32>>, pattern_size: usize) {
    let mut pattern_map: HashMap<String, HashSet<usize>> = HashMap::new();

    for (row_index, row) in matrix.iter().enumerate() {
        for col in 0..=row.len() - pattern_size {
            let pattern = row[col..col + pattern_size]
                .iter()
                .map(|num| num.to_string())
                .collect::<Vec<String>>()
                .join("-");

            pattern_map.entry(pattern)
                .or_insert_with(HashSet::new)
                .insert(row_index);
        }
    }

    println!("Repeated Patterns Found:");
    for (pattern, rows) in &pattern_map {
        if rows.len() > 1 {
            println!("{} appears {} times in rows: {}", 
                pattern, rows.len(), rows.iter().map(|r| r.to_string()).collect::<Vec<String>>().join(" "));
        }
    }
}

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

    let pattern_size = 3; // Looking for sequences of 3 numbers
    
    find_repeating_patterns(matrix, pattern_size);
}


  
   
/*
run:
   
Repeated Patterns Found:
1-3-2 appears 2 times in rows: 6 1
7-8-9 appears 3 times in rows: 6 4 1
6-7-8 appears 2 times in rows: 4 6
1-2-3 appears 5 times in rows: 4 0 3 5 2
9-4-5 appears 2 times in rows: 1 5
5-6-7 appears 2 times in rows: 4 6
4-5-6 appears 3 times in rows: 1 4 6
2-3-8 appears 2 times in rows: 2 0
   
*/

 

 



answered May 25 by avibootz
...