Skip to content

Instantly share code, notes, and snippets.

@rickycodes
Created December 1, 2022 17:24
Show Gist options
  • Save rickycodes/94f8836b3c1fe7a4307afb920941f2d8 to your computer and use it in GitHub Desktop.
Save rickycodes/94f8836b3c1fe7a4307afb920941f2d8 to your computer and use it in GitHub Desktop.
sudoku
use std::collections::HashSet;
struct Quad(Vec<Vec<Cell>>);
struct Row(Vec<Cell>);
struct Cell(u8);
impl Quad {
fn is_valid(&self) -> bool {
let mut values = HashSet::new();
for row in self.0.iter() {
for cell in row.iter() {
if values.contains(&cell.0) {
return false;
}
values.insert(cell.0);
}
}
true
}
}
impl Row {
fn is_valid(&self) -> bool {
let mut values = HashSet::new();
for cell in self.0.iter() {
if values.contains(&cell.0) {
return false;
}
values.insert(cell.0);
}
true
}
}
fn solve_sudoku(grid: Vec<Vec<Cell>>) -> Option<Vec<Vec<Cell>>> {
let mut quads = vec![];
let mut rows = vec![];
for i in (0..9).step_by(3) {
for j in (0..9).step_by(3) {
let quad = Quad(
grid[i..i + 3]
.iter()
.map(|row| row[j..j + 3].to_vec())
.collect(),
);
if !quad.is_valid() {
return None;
}
quads.push(quad);
}
}
for row in grid.iter() {
let row = Row(row.to_vec());
if !row.is_valid() {
return None;
}
rows.push(row);
}
// Solve the Sudoku puzzle using the quads and rows...
Some(grid)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment