arraysrustequality

Is there an easier way to check if two elements in a Rust array are equal?


I have an array:

let mut zobrist_pieces = [[0u64; 64]; 12];
for i in 0..12 {
    for j in 0..64 {
        zobrist_pieces[i][j] = rng.random();
    }
}

and I want to check if there is any way to find if two of the members are equal.


Solution

  • Iterate over the values in matrix and store them in a Map. If you find a value in Map, then you have found equal values.

    use rand::prelude::*;
    use std::collections::HashMap;
    
    fn main() {
        let mut rng = rand::rng();
        let mut zobrist_pieces = [[0u64; 64]; 12];
        let mut zobrist_pieces_map = HashMap::<u64,bool>::new();
    
        for i in 0..12 {
            for j in 0..64 {
                zobrist_pieces[i][j] = rng.random();
                let map_value = zobrist_pieces_map.get(&zobrist_pieces[i][j]).unwrap_or(&false);
                if *map_value == false {
                    zobrist_pieces_map.insert(zobrist_pieces[i][j], true);
                } else {
                    println!("Found equal value");
                }
            }
        }
    }
    
    

    Open in rust playground

    PS: Simplified version uses Set.

    use rand::prelude::*;
    use std::collections::HashSet;
    
    fn main() {
        let mut rng = rand::rng();
        let mut zobrist_pieces = [[0u64; 64]; 12];
        let mut zobrist_pieces_set = HashSet::<u64>::new();
    
        for i in 0..12 {
            for j in 0..64 {
                zobrist_pieces[i][j] = rng.random();
                let value_in_set = zobrist_pieces_set.contains(&zobrist_pieces[i][j]);
                if value_in_set == false {
                    zobrist_pieces_set.insert(zobrist_pieces[i][j]);
                } else {
                    println!("Found equal value");
                }
            }
        }
    }
    

    Open in rust playground