sudoku-solver/src/validator.rs
2024-06-20 22:50:06 -07:00

63 lines
1.4 KiB
Rust

use crate::{board::Board, square::Square};
pub enum BoardState {
Finished,
Broken(u8),
InProgress,
}
fn are_unique<T>(iter: T) -> bool
where
T: Iterator<Item = u8>,
{
let mut bitmap: bitmaps::Bitmap<10> = bitmaps::Bitmap::new();
for item in iter {
if bitmap.get(item as usize) {
return false;
}
bitmap.set(item as usize, true);
}
true
}
pub fn validate_board(board: &Board) -> BoardState {
for r in 0..9 {
if !are_unique(board.row(r).filter_map(|sq| match sq {
Square::Value(x) => Some(x),
_ => None,
})) {
// TODO: Add the index.
return BoardState::Broken(0);
}
}
for c in 0..9 {
if !are_unique(board.col(c).filter_map(|sq| match sq {
Square::Value(x) => Some(x),
_ => None,
})) {
// TODO: Add the index.
return BoardState::Broken(0);
}
}
for b in 0..9 {
if !are_unique(board.boxn(b).filter_map(|sq| match sq {
Square::Value(x) => Some(x),
_ => None,
})) {
// TODO: Add the index.
return BoardState::Broken(0);
}
}
if board.squares.iter().any(|sq| match sq {
Square::Marks(_) => true,
_ => false,
}) {
BoardState::InProgress
} else {
BoardState::Finished
}
}