Initial sudoku solver with parser and formatter.

This commit is contained in:
Drew Galbraith 2024-04-10 15:45:09 -07:00
commit 338309fde6
5 changed files with 99 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

7
Cargo.lock generated Normal file
View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "sudoku-solver"
version = "0.1.0"

8
Cargo.toml Normal file
View File

@ -0,0 +1,8 @@
[package]
name = "sudoku-solver"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

68
src/board.rs Normal file
View File

@ -0,0 +1,68 @@
use std::fmt::{self, Write};
pub enum Square {
Value(u8),
Options(Vec<u8>),
}
impl Square {
pub fn from_char(c: char) -> Square {
match c {
'1' => Square::Value(1),
'2' => Square::Value(2),
'3' => Square::Value(3),
'4' => Square::Value(4),
'5' => Square::Value(5),
'6' => Square::Value(6),
'7' => Square::Value(7),
'8' => Square::Value(8),
'9' => Square::Value(9),
'.' => Square::Options(vec![1, 2, 3, 4, 5, 6, 7, 8, 9]),
_ => panic!("Unexpected character in input: {}", c),
}
}
pub fn to_str(&self) -> String {
match self {
Square::Options(_) => " ".to_string(),
Square::Value(v) => v.to_string(),
}
}
}
pub struct Board {
squares: Vec<Square>,
}
impl Board {
pub fn from_string(str: &str) -> Board {
if str.len() != 81 {
panic!("Input string not length 81: got {}", str.len())
}
let mut squares = Vec::new();
for c in str.chars() {
squares.push(Square::from_char(c))
}
Board { squares }
}
}
impl fmt::Debug for Board {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("-------------\n")?;
for r in 0..9 {
f.write_char('|')?;
for c in 0..9 {
f.write_str(&self.squares[r * 9 + c].to_str())?;
if c == 2 || c == 5 || c == 8 {
f.write_char('|')?;
}
}
f.write_char('\n')?;
if r == 2 || r == 5 || r == 8 {
f.write_str("-------------\n")?;
}
}
Ok(())
}
}

15
src/main.rs Normal file
View File

@ -0,0 +1,15 @@
mod board;
fn main() {
let nyt_hard = "3...184.9\
8.47.....\
.....61..\
4....25.8\
..3.....4\
....4..2.\
...6.1...\
17.2.....\
5........";
let sudoku_board = board::Board::from_string(nyt_hard);
println!("{:#?}", sudoku_board);
}