Created
October 7, 2022 17:34
-
-
Save rklaehn/74c798f0fdd2a62de7f058e770dbc172 to your computer and use it in GitHub Desktop.
Sudoku, mostly written by github copilot
This file contains hidden or 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
//! Create a sudoku tester and make the test pass. | |
use std::{str::FromStr, fmt::Display}; | |
struct Sudoku { | |
grid: Vec<Vec<u8>>, | |
} | |
impl Sudoku { | |
fn valid(&self) -> bool { | |
// Check that the grid is 9x9 | |
if self.grid.len() != 9 { | |
return false; | |
} | |
for row in &self.grid { | |
if row.len() != 9 { | |
return false; | |
} | |
} | |
// Check that each row contains the digits 1-9 | |
for row in &self.grid { | |
let mut digits = [false; 9]; | |
for &digit in row { | |
if digit == 0 { | |
return false; | |
} | |
if digits[(digit - 1) as usize] { | |
return false; | |
} | |
digits[(digit - 1) as usize] = true; | |
} | |
} | |
// Check that each column contains the digits 1-9 | |
for col in 0..9 { | |
let mut digits = [false; 9]; | |
for row in &self.grid { | |
let digit = row[col]; | |
if digit == 0 { | |
return false; | |
} | |
if digits[(digit - 1) as usize] { | |
return false; | |
} | |
digits[(digit - 1) as usize] = true; | |
} | |
} | |
// Check that each 3x3 subgrid contains the digits 1-9 | |
for row in (0..9).step_by(3) { | |
for col in (0..9).step_by(3) { | |
let mut digits = [false; 9]; | |
for row_offset in 0..3 { | |
for col_offset in 0..3 { | |
let digit = self.grid[row + row_offset][col + col_offset]; | |
if digit == 0 { | |
return false; | |
} | |
if digits[(digit - 1) as usize] { | |
return false; | |
} | |
digits[(digit - 1) as usize] = true; | |
} | |
} | |
} | |
} | |
true | |
} | |
} | |
impl Display for Sudoku { | |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | |
for row in &self.grid { | |
for cell in row { | |
write!(f, "{}", cell)?; | |
} | |
writeln!(f)?; | |
} | |
Ok(()) | |
} | |
} | |
impl FromStr for Sudoku { | |
type Err = (); | |
fn from_str(s: &str) -> Result<Self, Self::Err> { | |
let grid = s | |
.lines() | |
.map(|line| { | |
line.chars() | |
.filter_map(|c| c.to_digit(10).map(|d| d as u8)) | |
.collect() | |
}) | |
.collect(); | |
Ok(Sudoku { grid }) | |
} | |
} | |
fn main() { | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::*; | |
#[test] | |
fn test_validate_sudoku() { | |
let sudoku: Sudoku = "534678912\n\ | |
672195348\n\ | |
198342567\n\ | |
859761423\n\ | |
426853791\n\ | |
713924856\n\ | |
961537284\n\ | |
287419635\n\ | |
345286177" | |
.parse() | |
.unwrap(); | |
println!("{}", sudoku); | |
assert!(sudoku.valid()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment