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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
//! Sudoku solving routines.

#[cfg(test)]
mod tests;

use std::iter::FusedIterator;

use super::board::*;
use bit_iter::BitIter;

/// Test whether a sudoku board state obeys the contraints of the game.
///
/// The constraints are:
///
/// * No digit 1-9 is repeated in any given row, column or square.
/// * Every cell contains a value from 0-9 inclusive.
///
/// Note that zeroes repesent unfilled cells, and do not count as duplicates.
///
/// ## Example
///
/// A board with a duplicate in the first column:
///
/// ```rust
/// # fn main() {
/// # use sudoku_solver::*;
/// let board = Board::from(&[[0u8; BOARD_SIZE]; BOARD_SIZE])
///     .with_cell(0, 0, 9)
///     .with_cell(0, 5, 9);
///
/// assert!(!valid(&board));
/// # }
/// ```
pub fn valid(b: &Board) -> bool {
    const PRECALC_MASKS: [u64; BOARD_SIZE + 1] = [
        0x00_0000_0001,
        0x00_0000_0010,
        0x00_0000_0100,
        0x00_0000_1000,
        0x00_0001_0000,
        0x00_0010_0000,
        0x00_0100_0000,
        0x00_1000_0000,
        0x01_0000_0000,
        0x10_0000_0000,
    ];

    for y in 0..BOARD_SIZE {
        for x in 0..BOARD_SIZE {
            if b.get_cell(x, y) > 9 {
                return false;
            }
        }
    }

    // Check rows.
    for y in 0..BOARD_SIZE {
        let mut acc = 0;

        for x in 0..BOARD_SIZE {
            acc += PRECALC_MASKS[b.get_cell(x, y) as usize];
        }

        if (acc & 0xee_eeee_eee0) != 0 {
            return false;
        }
    }

    // Check columns.
    for x in 0..BOARD_SIZE {
        let mut acc = 0;

        for y in 0..BOARD_SIZE {
            acc += PRECALC_MASKS[b.get_cell(x, y) as usize];
        }

        if (acc & 0xee_eeee_eee0) != 0 {
            return false;
        }
    }

    // Check squares.
    for square in 0..BOARD_SIZE {
        let mut acc = 0;

        let x = SQUARE_SIZE * (square / SQUARE_SIZE);
        let y = SQUARE_SIZE * (square % SQUARE_SIZE);

        for i in 0..BOARD_SIZE {
            acc += PRECALC_MASKS[b.get_cell(x + (i / 3), y + (i % 3)) as usize];
        }

        if (acc & 0xee_eeee_eee0) != 0 {
            return false;
        }
    }

    true
}

fn valid_choices_for_cell(b: &Board, x: usize, y: usize) -> u16 {
    let mut cs = 0b11_1111_1110u16;

    // Check row.
    for i in 0..BOARD_SIZE {
        cs &= !(1 << b.get_cell(i, y));
    }

    // Check column.
    for i in 0..BOARD_SIZE {
        cs &= !(1 << b.get_cell(x, i));
    }

    // Check square.
    let x = SQUARE_SIZE * (x / SQUARE_SIZE);
    let y = SQUARE_SIZE * (y / SQUARE_SIZE);
    for i in 0..BOARD_SIZE {
        cs &= !(1 << b.get_cell(x + (i / 3), y + (i % 3)));
    }

    cs
}

fn cell_with_fewest_candidates(b: &Board) -> Option<(usize, usize, u16)> {
    let mut min_x = 0;
    let mut min_y = 0;
    let mut min_candidates = 0;
    let mut min_count = BOARD_SIZE + 1;

    // Find the cell with the least number of possible valid values.
    for y in 0..BOARD_SIZE {
        for x in 0..BOARD_SIZE {
            if b.get_cell(x, y) == 0 {
                let cs = valid_choices_for_cell(b, x, y);

                if cs == 0 {
                    // No valid choices for this empty cell, so we need to backtrack.
                    return None;
                }

                let count = cs.count_ones() as usize;

                if count < min_count {
                    min_x = x;
                    min_y = y;
                    min_candidates = cs;
                    min_count = count;
                }
            }
        }
    }

    Some((min_x, min_y, min_candidates))
}

/// Solve a sudoku puzzle.
///
/// Returns an `Option<Board>` which is either `None`, if no solution could be found, or a `Some`
/// variant wrapping the first solution found.
///
/// ## Example
///
/// ```rust
/// # fn main() {
/// # use sudoku_solver::*;
/// let board = Board::from(&[
///     [0, 0, 0, 2, 6, 0, 7, 0, 1], // row 1
///     [6, 8, 0, 0, 7, 0, 0, 9, 0], // row 2
///     [1, 9, 0, 0, 0, 4, 5, 0, 0], // row 3
///     [8, 2, 0, 1, 0, 0, 0, 4, 0], // row 4
///     [0, 0, 4, 6, 0, 2, 9, 0, 0], // row 5
///     [0, 5, 0, 0, 0, 3, 0, 2, 8], // row 6
///     [0, 0, 9, 3, 0, 0, 0, 7, 4], // row 7
///     [0, 4, 0, 0, 5, 0, 0, 3, 6], // row 8
///     [7, 0, 3, 0, 1, 8, 0, 0, 0], // row 9
/// ]);
///
/// assert!(solve(&board).is_some());
/// # }
/// ```
pub fn solve(b: &Board) -> Option<Board> {
    SolutionIter::new(b).next()
}

/// An iterator which produces the set of solutions to a sudoku-style puzzle.
///
/// Strictly speaking, sudokus should have only one solution.  However, it is possible to construct
/// sudoku-style puzzles with multiple solutions.  `SolutionIter` provides a means of generating
/// such solutions lazily.
///
/// ## Example
///
/// ```rust
/// # fn main() {
/// # use sudoku_solver::*;
/// let mut solutions = SolutionIter::new(&Board::from(&[
///     [9, 0, 6, 0, 7, 0, 4, 0, 3], // row 1
///     [0, 0, 0, 4, 0, 0, 2, 0, 0], // row 2
///     [0, 7, 0, 0, 2, 3, 0, 1, 0], // row 3
///     [5, 0, 0, 0, 0, 0, 1, 0, 0], // row 4
///     [0, 4, 0, 2, 0, 8, 0, 6, 0], // row 5
///     [0, 0, 3, 0, 0, 0, 0, 0, 5], // row 6
///     [0, 3, 0, 7, 0, 0, 0, 5, 0], // row 7
///     [0, 0, 7, 0, 0, 5, 0, 0, 0], // row 8
///     [4, 0, 5, 0, 1, 0, 7, 0, 8], // row 9
/// ]));
///
/// assert_eq!(solutions.next(), Some(Board::from(&[
///     [9, 2, 6, 5, 7, 1, 4, 8, 3], // row 1
///     [3, 5, 1, 4, 8, 6, 2, 7, 9], // row 2
///     [8, 7, 4, 9, 2, 3, 5, 1, 6], // row 3
///     [5, 8, 2, 3, 6, 7, 1, 9, 4], // row 4
///     [1, 4, 9, 2, 5, 8, 3, 6, 7], // row 5
///     [7, 6, 3, 1, 4, 9, 8, 2, 5], // row 6
///     [2, 3, 8, 7, 9, 4, 6, 5, 1], // row 7
///     [6, 1, 7, 8, 3, 5, 9, 4, 2], // row 8
///     [4, 9, 5, 6, 1, 2, 7, 3, 8], // row 9
/// ])));
///
/// assert_eq!(solutions.next(), Some(Board::from(&[
///     [9, 2, 6, 5, 7, 1, 4, 8, 3], // row 1
///     [3, 5, 1, 4, 8, 6, 2, 7, 9], // row 2
///     [8, 7, 4, 9, 2, 3, 5, 1, 6], // row 3
///     [5, 8, 2, 3, 6, 7, 1, 9, 4], // row 4
///     [1, 4, 9, 2, 5, 8, 3, 6, 7], // row 5
///     [7, 6, 3, 1, 9, 4, 8, 2, 5], // row 6
///     [2, 3, 8, 7, 4, 9, 6, 5, 1], // row 7
///     [6, 1, 7, 8, 3, 5, 9, 4, 2], // row 8
///     [4, 9, 5, 6, 1, 2, 7, 3, 8], // row 9
/// ])));
///
/// assert_eq!(solutions.next(), None);
/// # }
/// ```
#[derive(Debug)]
pub struct SolutionIter {
    first: bool,
    board: Board,
    stack: Vec<(usize, usize, BitIter<u16>)>,
}

impl SolutionIter {
    /// Construct a `SolutionIter` value from a [`Board`].
    ///
    /// ## Example
    ///
    /// ```rust
    /// # fn main() {
    /// # use sudoku_solver::*;
    /// let board = Board::from(&[
    ///     [9, 0, 6, 0, 7, 0, 4, 0, 3], // row 1
    ///     [0, 0, 0, 4, 0, 0, 2, 0, 0], // row 2
    ///     [0, 7, 0, 0, 2, 3, 0, 1, 0], // row 3
    ///     [5, 0, 0, 0, 0, 0, 1, 0, 0], // row 4
    ///     [0, 4, 0, 2, 0, 8, 0, 6, 0], // row 5
    ///     [0, 0, 3, 0, 0, 0, 0, 0, 5], // row 6
    ///     [0, 3, 0, 7, 0, 0, 0, 5, 0], // row 7
    ///     [0, 0, 7, 0, 0, 5, 0, 0, 0], // row 8
    ///     [4, 0, 5, 0, 1, 0, 7, 0, 8], // row 9
    /// ]);
    ///
    /// let solutions = SolutionIter::new(&board);
    ///
    /// assert_eq!(solutions.count(), 2);
    /// # }
    /// ```
    pub fn new(board: &Board) -> Self {
        Self {
            first: true,
            board: *board,
            stack: Vec::with_capacity(BOARD_SIZE * BOARD_SIZE),
        }
    }
}

/// `From` implementation for `SolutionIter`.
impl From<Board> for SolutionIter {
    fn from(board: Board) -> Self {
        Self::new(&board)
    }
}

/// `Iterator` implementation for `SolutionIter`.
impl Iterator for SolutionIter {
    type Item = Board;

    fn next(&mut self) -> Option<Self::Item> {
        if self.first {
            self.first = false;

            if valid(&self.board) {
                if let Some((x, y, values)) = cell_with_fewest_candidates(&self.board) {
                    if values == 0 {
                        return Some(self.board);
                    }

                    self.stack.push((x, y, values.into()));
                }
            }
        }

        if let Some((mut x, mut y, mut values)) = self.stack.pop() {
            loop {
                if let Some(value) = values.next() {
                    self.board.set_cell(x, y, value as u8);

                    if let Some(cs) = cell_with_fewest_candidates(&self.board) {
                        self.stack.push((x, y, values));

                        if cs.2 == 0 {
                            return Some(self.board);
                        }

                        x = cs.0;
                        y = cs.1;
                        values = cs.2.into();
                    }
                } else {
                    self.board.set_cell(x, y, 0);

                    if let Some(cs) = self.stack.pop() {
                        x = cs.0;
                        y = cs.1;
                        values = cs.2;
                    } else {
                        return None;
                    }
                }
            }
        } else {
            None
        }
    }
}

/// `FusedIterator` implementation for `SolutionIter`.
impl FusedIterator for SolutionIter {}