Created
December 1, 2022 17:24
-
-
Save rickycodes/94f8836b3c1fe7a4307afb920941f2d8 to your computer and use it in GitHub Desktop.
sudoku
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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