sudoku/
sudoku.rs

1#![allow(clippy::print_stdout)]
2
3use algx::Solver;
4
5fn main() {
6    let rows = create_sudoku_exact_cover();
7
8    let solver = Solver::new(rows, vec![]);
9
10    for (i, solution) in solver.enumerate() {
11        let mut sudoku: [[u8; 9]; 9] = Default::default();
12        for (x, y, num) in solution.into_iter().map(x_y_num_from_row_index) {
13            sudoku[y][x] = num as u8;
14        }
15
16        println!("-------------------------");
17        for rows in sudoku.chunks(3) {
18            for row in rows {
19                for col in row.chunks(3) {
20                    print!("| ");
21                    for num in col {
22                        print!("{} ", num);
23                    }
24                }
25                println!("|");
26            }
27            println!("-------------------------");
28        }
29
30        println!();
31
32        if i == 0 {
33            println!("Press enter to show the next solution");
34        }
35
36        std::io::stdin().read_line(&mut String::new()).ok();
37    }
38}
39
40fn create_sudoku_exact_cover_row(y: &usize, x: &usize, num: &usize) -> [usize; 4] {
41    [
42        y * 9 + x,
43        (9 * 9) + (x * 9) + num,
44        (9 * 9) * 2 + (y * 9) + num,
45        (9 * 9) * 3 + (((y / 3) * 3 + (x / 3)) * 9 + num),
46    ]
47}
48
49fn create_sudoku_exact_cover() -> Vec<Vec<usize>> {
50    let mut rows = vec![];
51
52    for y in 0..9 {
53        for x in 0..9 {
54            for num in 0..9 {
55                rows.push(create_sudoku_exact_cover_row(&y, &x, &num).to_vec());
56            }
57        }
58    }
59    rows
60}
61
62fn x_y_num_from_row_index(i: usize) -> (usize, usize, usize) {
63    let num = i % 9 + 1;
64    let y = (i / 9) % 9;
65    let x = i / (9 * 9);
66
67    (x, y, num)
68}