domino_lib/functionalities/
generate.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
use rand::Rng;
use crate::types::{graph_types::graph::Graph, Puzzle, Solution, Tile};

use super::graph_common::find_eulerian_cycle;

pub fn generate_puzzle(n: usize, minimum_removals: usize, random: bool) -> Puzzle {
    let graph = Graph::regular(n);
    let eulerian_cycle = find_eulerian_cycle(&graph, random);
    let solution: Solution = eulerian_cycle
    .windows(2).map(|arc| {
        Tile(arc[0].clone().try_into().unwrap(), arc[1].clone().try_into().unwrap())
    })
    .collect();
    let mut puzzle: Puzzle = solution.into_iter()
        .map(|tile| Some(tile))
        .collect();
    if random {
        let mut seed = rand::thread_rng();        
        if puzzle.len() > 0 {
            for _ in 0..=minimum_removals {
                let mut index = seed.gen_range(0..puzzle.len());
                while puzzle[index].is_none() {
                    index = seed.gen_range(0..puzzle.len());
                }
                puzzle[index] = None;
            }    
        }    
    } else {
        puzzle[1] = None;
    }
    puzzle
}