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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
use rand::Rng;

pub const N: usize = 9;
pub const SRN: usize = 3;

#[derive(Clone, Copy)]
pub struct Cell {
    pub num: u8,
    pub locked: bool,
}
type Grid = [[Cell; N]; N];

pub struct SudokuBoard {
    pub cells: Grid,
}

impl SudokuBoard {
    /// Create an empty board with all cells "locked"
    pub fn new() -> Self {
        Self {
            cells: [[Cell {
                num: 0,
                locked: true,
            }; N]; N],
        }
    }

    /// Fill board completely with solved state
    pub fn fill(&mut self) {
        self.fill_diagonal();
        self.fill_remaining(0, SRN);
    }

    fn fill_diagonal(&mut self) {
        for i in 0..SRN {
            self.fill_box(i * SRN, i * SRN);
        }
    }

    /// Returns false if given SRN x SRN block contains num.
    pub fn unused_in_box(grid: Grid, row_start: usize, col_start: usize, num: u8) -> bool {
        for i in 0..SRN {
            for j in 0..SRN {
                if grid[row_start + i][col_start + j].num == num {
                    return false;
                }
            }
        }
        return true;
    }

    fn fill_box(&mut self, row: usize, col: usize) {
        let mut rng = rand::thread_rng();
        let mut num: Option<u8> = None;
        for i in 0..SRN {
            for j in 0..SRN {
                while num == None || !Self::unused_in_box(self.cells, row, col, num.unwrap()) {
                    num = Some(rng.gen_range(0..=N as u8));
                }
                self.cells[row + i][col + j].num = num.unwrap();
            }
        }
    }

    /// Check if safe to put in cell
    pub fn check_if_safe(grid: Grid, i: usize, j: usize, num: u8) -> bool {
        num == 0
            || (Self::unused_in_row(grid, i, num)
                && Self::unused_in_col(grid, j, num)
                && Self::unused_in_box(grid, i - i % SRN, j - j % SRN, num))
    }

    pub fn unused_in_row(grid: Grid, i: usize, num: u8) -> bool {
        for j in 0..N {
            if grid[i][j].num == num {
                return false;
            }
        }
        return true;
    }

    pub fn unused_in_col(grid: Grid, j: usize, num: u8) -> bool {
        for i in 0..N {
            if grid[i][j].num == num {
                return false;
            }
        }
        return true;
    }

    /// A recursive function to fill remaining
    /// matrix
    pub fn fill_remaining(&mut self, mut i: usize, mut j: usize) -> bool {
        if j >= N && i < N - 1 {
            i += 1;
            j = 0;
        }
        if i >= N && j >= N {
            return true;
        }
        if i < SRN {
            if j < SRN {
                j = SRN;
            }
        } else if i < N - SRN {
            if j == i / SRN * SRN {
                j += SRN;
            }
        } else {
            if j == N - SRN {
                i += 1;
                j = 0;
                if i >= N {
                    return true;
                }
            }
        }

        for num in 1..=N as u8 {
            if Self::check_if_safe(self.cells, i, j, num) {
                self.cells[i][j].num = num;
                if self.fill_remaining(i, j + 1) {
                    return true;
                }
                self.cells[i][j].num = 0;
                self.cells[i][j].locked = false;
            }
        }

        false
    }

    /// Get the amount of unique solutions a board has
    pub fn solve(mut grid: Grid, mut counter: u32) -> u32 {
        let mut row = 0;
        let mut col = 0;
        for i in 0..81 {
            row = i / N;
            col = i % N;
            if grid[row][col].num == 0 {
                for num in 1..10 {
                    // Check if it is safe to place
                    // the num (1-N)  in the
                    // given row ,col ->we move to next column
                    if Self::check_if_safe(grid, row, col, num) {
                        /*  assigning the num in the current
                        (row,col)  position of the grid and
                        assuming our assigned num in the position
                        is correct */
                        grid[row][col].num = num;
                        if Self::check_filled(grid) {
                            counter += 1;
                            break;
                        } else {
                            // Checking for next
                            // possibility with next column
                            return Self::solve(grid, counter);
                        }
                    }
                    /* removing the assigned num , since our
                    assumption was wrong , and we go for next
                    assumption with diff num value   */
                }
                break;
            }
        }
        grid[row][col].num = 0;
        grid[row][col].locked = false;
        return counter;
    }

    /// Check if the board has no mistakes
    pub fn check_valid(mut grid: Grid) -> bool {
        for i in 0..N {
            for j in 0..N {
                let original = grid[i][j].num;
                grid[i][j].num = 0;
                if !Self::check_if_safe(grid, i, j, original) {
                    return false;
                }
                grid[i][j].num = original;
            }
        }
        true
    }

    /// Check if the board is solved
    pub fn check_solved(grid: Grid) -> bool {
        Self::check_filled(grid) && Self::check_valid(grid)
    }

    /// Check if the board is completely filled
    pub fn check_filled(grid: Grid) -> bool {
        for row in 0..N {
            for col in 0..N {
                if grid[row][col].num == 0 {
                    return false;
                }
            }
        }

        true
    }

    /// Remove cells from the filled solved board to make a puzzle
    pub fn remove_cells(&mut self, mut attempts: u32) {
        let mut rng = rand::thread_rng();

        while attempts > 0 {
            // Select a random cell that is not already empty
            let mut row = rng.gen_range(0..N);
            let mut col = rng.gen_range(0..N);
            while self.cells[row][col].num == 0 {
                row = rng.gen_range(0..N);
                col = rng.gen_range(0..N);
            }

            //Remember its cell value in case we need to put it back
            let backup = self.cells[row][col].clone();
            self.cells[row][col].num = 0;
            self.cells[row][col].locked = false;

            // Take a full copy of the grid
            let copy_grid = self.cells.clone();

            let counter = Self::solve(copy_grid, 0);
            // Count the number of solutions that this grid has (using a backtracking approach implemented in the solveGrid() function)
            //If the number of solution is different from 1 then we need to cancel the change by putting the value we took away back in the grid
            if counter != 1 {
                self.cells[row][col] = backup;
                //We could stop here, but we can also have another attempt with a different cell just to try to remove more numbers
                attempts -= 1;
            }
        }
    }

    /// Display the board in stdout
    pub fn display(&self) {
        Self::display_grid(&self.cells);
    }

    /// Display grid in stdout
    pub fn display_grid(grid: &Grid) {
        println!(
            "{}",
            grid.map(|a| {
                a.map(|a| match a.num {
                    0 => " ".to_string(),
                    _ => a.num.to_string(),
                })
                .join(" ")
            })
            .join("\n")
        );
    }
}

#[cfg(test)]
mod tests {
    use crate::{SudokuBoard, N};

    #[test]
    fn check_solved() {
        let mut board = SudokuBoard::new();
        board.fill();
        assert!(SudokuBoard::check_solved(board.cells));

        board.cells[0][0].num = N as u8 - board.cells[0][0].num;
        assert!(!SudokuBoard::check_solved(board.cells));

        board.cells[0][0].num = 0;
        assert!(!SudokuBoard::check_solved(board.cells));
        assert!(SudokuBoard::check_valid(board.cells));
    }
}