soku 0.1.1

Easy sudoku generation and solving
Documentation
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
use std::{
    collections::HashSet,
    fmt::{Display, Write},
    hash::Hash,
    slice::Chunks,
    str::FromStr,
};

use bitflags::bitflags;
use derive_more::{Deref, Display};
use rand::Rng;
use thiserror::Error;

use crate::prelude::{
    BruteForceSolver, Generate, LatinSquares, Solve, SudokuConfig, DIGITS, DIGIT_INDICES,
    GRID_SIZE, HOUSE_SIZE, SQUARE_SIZE,
};

// TODO: tests
// TODO: docs

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Sudoku(pub [Cell; GRID_SIZE]);

impl Sudoku {
    #[must_use]
    pub fn new_empty() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn new_filled(config: SudokuConfig) -> Self {
        Self::new_filled_with_generator(LatinSquares, config)
    }

    #[must_use]
    pub fn new_unique(config: SudokuConfig) -> Self {
        Self::new_with_generator(LatinSquares, config)
    }

    #[inline]
    #[must_use]
    pub const fn size(&self) -> usize {
        self.0.len()
    }

    #[must_use]
    pub fn new_with_generator(generator: impl Generate, config: SudokuConfig) -> Self {
        generator.generate(config)
    }

    #[must_use]
    pub fn new_filled_with_generator(generator: impl Generate, config: SudokuConfig) -> Self {
        generator.generate_filled(config)
    }

    #[must_use]
    pub const fn into_inner(self) -> [Cell; GRID_SIZE] {
        self.0
    }

    #[must_use]
    pub const fn as_slice(&self) -> &[Cell] {
        &self.0
    }

    #[must_use]
    pub fn as_slice_mut(&mut self) -> &mut [Cell] {
        &mut self.0
    }

    pub fn solve_with(&mut self, solver: impl Solve) -> bool {
        solver.solve(self)
    }

    pub fn count_solutions(&self, limit: usize) -> usize {
        if self.is_filled() {
            return 1;
        }

        let mut solutions = Vec::with_capacity(limit);

        for (i, cell) in self.cells().enumerate().filter(|(_, c)| c.digit.is_none()) {
            for digit in self.cell_candidates(i).digits() {
                let mut sudoku = self.clone();

                sudoku.set_cell(cell.coord, digit);

                let solved = sudoku.solve_with(BruteForceSolver::new());

                if solved && (solutions.is_empty() || solutions.iter().any(|s| s != &sudoku)) {
                    if solutions.len() == limit {
                        return solutions.len();
                    } else {
                        solutions.push(sudoku);
                    }
                }
            }
        }

        solutions.len()
    }

    pub fn is_unique(&self) -> bool {
        self.count_solutions(2) == 1
    }

    #[must_use]
    pub fn count_filled_cells(&self) -> usize {
        self.0.iter().filter_map(|cell| cell.digit).count()
    }

    #[must_use]
    pub fn count_unfilled_cells(&self) -> usize {
        self.0.len() - self.count_filled_cells()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.count_filled_cells() == 0
    }

    #[must_use]
    pub fn is_filled(&self) -> bool {
        self.count_filled_cells() == self.0.len()
    }

    #[must_use]
    pub fn cell<I: SudokuIndex>(&self, i: I) -> Option<&Cell> {
        self.0.get(i.into_index())
    }

    pub fn cell_mut<I: SudokuIndex>(&mut self, i: I) -> Option<&mut Cell> {
        self.0.get_mut(i.into_index())
    }

    pub fn cells(&self) -> impl Iterator<Item = &'_ Cell> {
        self.0.iter()
    }

    pub fn set_cell<I: SudokuIndex>(&mut self, i: I, digit: Digit) -> Option<&mut Cell> {
        let mut cell = self.cell_mut(i.into_index())?;
        cell.digit = Some(digit);
        Some(cell)
    }

    pub fn with_cell<I: SudokuIndex>(mut self, i: I, digit: Digit) -> Self {
        self.set_cell(i, digit);
        self
    }

    pub fn clear_cell<I: SudokuIndex>(&mut self, i: I) -> Option<&mut Cell> {
        let mut cell = self.cell_mut(i.into_index())?;
        cell.digit = None;
        Some(cell)
    }

    #[inline]
    pub fn cells_mut(&mut self) -> impl Iterator<Item = &'_ mut Cell> {
        self.0.iter_mut()
    }

    pub fn row(&self, index: usize) -> impl Iterator<Item = &'_ Cell> {
        Self::assert_house_index(index);
        self.0.iter().skip(index * HOUSE_SIZE).take(HOUSE_SIZE)
    }

    pub fn row_mut(&mut self, index: usize) -> impl Iterator<Item = &'_ mut Cell> {
        Self::assert_house_index(index);
        self.0.iter_mut().skip(index * HOUSE_SIZE).take(HOUSE_SIZE)
    }

    pub fn rows(&self) -> Chunks<'_, Cell> {
        self.0.chunks(HOUSE_SIZE)
    }

    pub fn col(&self, index: usize) -> impl Iterator<Item = &'_ Cell> {
        Self::assert_house_index(index);

        self.0
            .iter()
            .enumerate()
            .filter_map(move |(cell_index, cell)| {
                if Coord::from_index(cell_index).col() == index {
                    Some(cell)
                } else {
                    None
                }
            })
    }

    pub fn col_mut(&mut self, index: usize) -> impl Iterator<Item = &'_ mut Cell> {
        Self::assert_house_index(index);

        self.0
            .iter_mut()
            .enumerate()
            .filter_map(move |(cell_index, cell)| {
                if Coord::from_index(cell_index).col() == index {
                    Some(cell)
                } else {
                    None
                }
            })
    }

    #[must_use]
    pub fn cols(&self) -> Vec<impl Iterator<Item = &'_ Cell>> {
        DIGIT_INDICES.map(|i| self.col(i)).collect()
    }

    pub fn square<I: SudokuIndex>(&self, i: I) -> impl Iterator<Item = &'_ Cell> {
        let index = i.into_index_of(SQUARE_SIZE);
        Self::assert_house_index(index);

        let square_indices = Self::square_indices(Coord::from_index_of(index, SQUARE_SIZE));

        self.0.iter().enumerate().filter_map(move |(index, cell)| {
            if square_indices.contains(&index) {
                Some(cell)
            } else {
                None
            }
        })
    }

    pub fn square_mut<I: SudokuIndex>(&mut self, i: I) -> impl Iterator<Item = &'_ mut Cell> {
        let index = i.into_index_of(SQUARE_SIZE);
        Self::assert_house_index(index);

        let square_indices = Self::square_indices(Coord::from_index_of(index, SQUARE_SIZE));

        self.0
            .iter_mut()
            .enumerate()
            .filter_map(move |(index, cell)| {
                if square_indices.contains(&index) {
                    Some(cell)
                } else {
                    None
                }
            })
    }

    pub fn square_of_cell<I: SudokuIndex>(&self, i: I) -> impl Iterator<Item = &'_ Cell> {
        let coord = Coord::from_index(i.into_index());
        self.square(Self::cell_coord_to_square_coord(coord))
    }

    pub fn square_mut_of_cell<I: SudokuIndex>(
        &mut self,
        i: I,
    ) -> impl Iterator<Item = &'_ mut Cell> {
        let coord = Coord::from_index(i.into_index());
        self.square_mut(Self::cell_coord_to_square_coord(coord))
    }

    const fn cell_coord_to_square_coord(cell_coord: Coord) -> Coord {
        Coord(
            cell_coord.row() / SQUARE_SIZE,
            cell_coord.col() / SQUARE_SIZE,
        )
    }

    pub const fn square_indices(Coord(row, col): Coord) -> [usize; HOUSE_SIZE] {
        let square_row = row * HOUSE_SIZE * SQUARE_SIZE;
        let square_col = col * SQUARE_SIZE;

        let square_index = square_row + square_col;

        [
            square_index,
            square_index + 1,
            square_index + 2,
            //
            square_index + HOUSE_SIZE,
            square_index + HOUSE_SIZE + 1,
            square_index + HOUSE_SIZE + 2,
            //
            square_index + HOUSE_SIZE * 2,
            square_index + HOUSE_SIZE * 2 + 1,
            square_index + HOUSE_SIZE * 2 + 2,
        ]
    }

    pub const fn square_indices_of_cell(Coord(row, col): Coord) -> [usize; HOUSE_SIZE] {
        Self::square_indices(Coord(row / SQUARE_SIZE, col / SQUARE_SIZE))
    }

    pub fn cell_candidates<I: SudokuIndex>(&self, i: I) -> Candidates {
        let index = i.into_index();
        let mut candidates = Candidates::all();

        let Coord(row, col) = Coord::from_index(index);

        for cell in self
            .row(row)
            .chain(self.col(col))
            .chain(self.square_of_cell(index))
        {
            if let Some(digit) = cell.digit {
                candidates.remove(digit);
            }
        }

        candidates
    }

    pub fn all_candidates(&self) -> Vec<Candidates> {
        self.cells()
            .enumerate()
            .map(|(i, cell)| {
                if cell.digit.is_some() {
                    Candidates::empty()
                } else {
                    self.cell_candidates(i)
                }
            })
            .collect::<Vec<_>>()
    }

    pub fn solve_all_candidates(&mut self) {
        let all_candidates = self.all_candidates();

        self.cells_mut()
            .enumerate()
            .for_each(|(i, cell)| cell.candidates = all_candidates[i]);
    }

    #[must_use]
    pub fn is_valid(&self) -> bool {
        fn house_is_unique<'a>(house_iter: impl Iterator<Item = &'a Cell>) -> bool {
            let mut used = HashSet::new();
            house_iter
                .filter(|cell| cell.digit.is_some())
                .all(move |cell| used.insert(cell))
        }

        self.rows().all(|row| house_is_unique(row.iter()))
            && self.cols().into_iter().all(house_is_unique)
            && DIGIT_INDICES.map(|i| self.square(i)).all(house_is_unique)
    }

    #[inline]
    #[track_caller]
    fn assert_house_index(index: usize) {
        assert!(
            index < HOUSE_SIZE,
            "house index must be between 0 and {}, got {} instead",
            HOUSE_SIZE - 1,
            index
        );
    }

    pub fn to_str_line(&self) -> String {
        self.cells()
            .map(|cell| cell.digit.map_or('0', |d| char::from_digit((*d).into(), 10).unwrap()))
            .collect::<String>()
    }
}

impl From<[Cell; GRID_SIZE]> for Sudoku {
    fn from(value: [Cell; GRID_SIZE]) -> Self {
        Self(value)
    }
}

impl TryFrom<Vec<Cell>> for Sudoku {
    type Error = Vec<Cell>;

    fn try_from(value: Vec<Cell>) -> Result<Self, Self::Error> {
        Ok(Self(value.try_into()?))
    }
}

impl Default for Sudoku {
    fn default() -> Self {
        let mut cells = [Cell::default(); GRID_SIZE];

        for (index, cell) in cells.iter_mut().enumerate() {
            cell.coord = Coord::from_index(index);
        }

        Self(cells)
    }
}

impl Display for Sudoku {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        const PIPE: char = '|';

        f.write_str(".-----.-----.-----.\n")?;

        for (row_index, row) in self.rows().enumerate() {
            f.write_char(PIPE)?;

            for (cell_index, cell) in row.iter().enumerate() {
                match &cell.digit {
                    Some(digit) => write!(f, "{}", *digit)?,
                    None => f.write_char('.')?,
                }

                if (cell_index + 1) % SQUARE_SIZE == 0 {
                    f.write_char(PIPE)?;
                } else {
                    f.write_char(' ')?;
                }
            }

            f.write_char('\n')?;

            if row_index < HOUSE_SIZE - 1 && (row_index + 1) % SQUARE_SIZE == 0 {
                f.write_str(":----- ----- -----:\n")?;
            }
        }

        f.write_str("'-----'-----'-----'")?;

        Ok(())
    }
}

// TODO: from_str
impl FromStr for Sudoku {
    type Err = ParseError;

    fn from_str(_s: &str) -> Result<Self, Self::Err> {
        todo!()
        // Err(ParseError::InvalidChar {
        //     char: 'F',
        //     index: 0,
        // })
    }
}

#[derive(Error, Debug)]
pub enum ParseError {
    #[error("invalid character `{char}` at index {index}")]
    InvalidChar { char: char, index: usize },
}

#[derive(Debug, Default, PartialEq, Eq, Hash, Clone, Copy)]
pub struct Cell {
    pub coord: Coord,
    pub digit: Option<Digit>,
    pub candidates: Candidates,
    pub is_given: bool,
}

#[derive(Debug, Display, Default, Deref, PartialEq, Eq, Hash, Clone, Copy)]
pub struct Digit(pub u8);

impl Digit {
    #[must_use]
    #[inline]
    pub fn is_valid(value: u8) -> bool {
        DIGITS.contains(&value)
    }

    pub fn new(value: u8) -> SudokuResult<Self> {
        Self::try_from(value)
    }

    #[must_use]
    #[inline]
    pub const fn new_unchecked(value: u8) -> Self {
        Self(value)
    }
}

impl TryFrom<u8> for Digit {
    type Error = SudokuError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        if Self::is_valid(value) {
            Ok(Self(value))
        } else {
            Err(SudokuError::InvalidDigit(value))
        }
    }
}

#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub struct Candidates(CandidatesInner);

impl Candidates {
    #[must_use]
    #[inline]
    pub const fn empty() -> Self {
        Self(CandidatesInner::empty())
    }

    #[must_use]
    #[inline]
    pub const fn all() -> Self {
        Self(CandidatesInner::ALL)
    }

    pub fn add(&mut self, digit: Digit) {
        self.0.insert(digit.into());
    }

    pub fn remove(&mut self, digit: Digit) {
        self.0.remove(digit.into());
    }

    pub fn toggle(&mut self, digit: Digit) {
        self.0.toggle(digit.into());
    }

    #[must_use]
    pub fn contains(&self, digit: Digit) -> bool {
        self.0.contains(digit.into())
    }

    // PERF: inefficient
    pub fn digits(&self) -> impl Iterator<Item = Digit> + '_ {
        DIGITS
            .map(Digit::new_unchecked)
            .filter(|digit| self.contains(*digit))
    }

    // PERF: inefficient
    pub fn count(&self) -> usize {
        self.digits().count()
    }
}

impl Default for Candidates {
    fn default() -> Self {
        Self(CandidatesInner::empty())
    }
}

impl From<Digit> for Candidates {
    fn from(value: Digit) -> Self {
        let mut candidates = Self::empty();
        candidates.add(value);
        candidates
    }
}

bitflags! {
    struct CandidatesInner: usize {
        const _1 = 0b0000_0000_0000_0001;
        const _2 = 0b0000_0000_0000_0010;
        const _3 = 0b0000_0000_0000_0100;
        const _4 = 0b0000_0000_0000_1000;
        const _5 = 0b0000_0000_0001_0000;
        const _6 = 0b0000_0000_0010_0000;
        const _7 = 0b0000_0000_0100_0000;
        const _8 = 0b0000_0000_1000_0000;
        const _9 = 0b0000_0001_0000_0000;
        const ALL = Self::_1.bits | Self::_2.bits | Self::_3.bits | Self::_4.bits
                    | Self::_5.bits | Self::_6.bits | Self::_7.bits | Self::_8.bits | Self::_9.bits;
    }
}

impl From<Digit> for CandidatesInner {
    fn from(value: Digit) -> Self {
        match value.0 {
            1 => Self::_1,
            2 => Self::_2,
            3 => Self::_3,
            4 => Self::_4,
            5 => Self::_5,
            6 => Self::_6,
            7 => Self::_7,
            8 => Self::_8,
            9 => Self::_9,
            _ => unreachable!(),
        }
    }
}

#[derive(Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub struct Coord(pub usize, pub usize);

impl Coord {
    #[inline]
    #[must_use]
    pub fn random(rng: &mut impl Rng) -> Self {
        let random_row = rng.gen_range(DIGIT_INDICES);
        let random_col = rng.gen_range(DIGIT_INDICES);
        Self(random_row, random_col)
    }

    #[inline]
    #[must_use]
    pub const fn from_index(index: usize) -> Self {
        Self::from_index_of(index, HOUSE_SIZE)
    }

    #[inline]
    #[must_use]
    pub const fn from_index_of(index: usize, size: usize) -> Self {
        Self(index / size, index % size)
    }

    #[inline]
    #[must_use]
    pub const fn row(&self) -> usize {
        self.0
    }

    #[inline]
    #[must_use]
    pub const fn col(&self) -> usize {
        self.1
    }

    #[inline]
    #[must_use]
    pub const fn with_row(self, row: usize) -> Self {
        Self(row, self.col())
    }

    #[inline]
    #[must_use]
    pub const fn with_col(self, col: usize) -> Self {
        Self(self.row(), col)
    }
}

pub trait SudokuIndex
where
    Self: Sized,
{
    fn into_index_of(self, size: usize) -> usize;

    fn into_index(self) -> usize {
        self.into_index_of(HOUSE_SIZE)
    }
}

impl SudokuIndex for usize {
    #[inline]
    fn into_index_of(self, _: usize) -> usize {
        self
    }
}

impl SudokuIndex for Coord {
    #[inline]
    #[must_use]
    fn into_index_of(self, size: usize) -> usize {
        (self.row() * size) + self.col()
    }
}

pub type SudokuResult<T> = Result<T, SudokuError>;

#[derive(Error, Debug)]
pub enum SudokuError {
    #[error("digit must be between 1 and 9, got {0}")]
    InvalidDigit(u8),
}