Beginning of sudoku chapter 7 with SDM loading

This commit is contained in:
2022-11-25 15:37:57 -05:00
parent 8f38a3b271
commit 7d2ac20ce1
7 changed files with 233 additions and 5 deletions

View File

@@ -2,6 +2,7 @@
const SIZE: usize = 9;
#[derive(Debug, PartialEq)]
pub struct Gameboard {
pub cells: [[u8; SIZE]; SIZE],
}
@@ -12,4 +13,68 @@ impl Gameboard {
cells: [[0; SIZE]; SIZE],
}
}
pub fn char(&self, ind: [usize; 2]) -> Option<char> {
Some(match self.cells[ind[1]][ind[0]] {
1 => '1',
2 => '2',
3 => '3',
4 => '4',
5 => '5',
6 => '6',
7 => '7',
8 => '8',
9 => '9',
_ => return None,
})
}
pub fn set(&mut self, ind: [usize; 2], val: u8) {
self.cells[ind[1]][ind[0]] = val;
}
pub fn load_sdm(filename: &str) -> Self {
use std::fs::read_to_string;
let data = read_to_string(filename).expect("failed to read SDM file");
let mut cells = [[0; SIZE]; SIZE];
let mut row = 0;
let mut col = 0;
for c in data.chars() {
if col == SIZE {
col = 0;
row += 1;
}
if let Some(d) = c.to_digit(10) {
cells[row][col] = d as u8;
col += 1;
}
}
Self { cells }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn load_sdm() {
let got = Gameboard::load_sdm("static/puzzle.sdm");
let want = Gameboard {
cells: [
[0, 1, 6, 4, 0, 0, 0, 0, 0],
[2, 0, 0, 0, 0, 9, 0, 0, 0],
[4, 0, 0, 0, 0, 0, 0, 6, 2],
[0, 7, 0, 2, 3, 0, 1, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 3],
[0, 0, 3, 0, 8, 7, 0, 4, 0],
[9, 6, 0, 0, 0, 0, 0, 0, 5],
[0, 0, 0, 8, 0, 0, 0, 0, 7],
[0, 0, 0, 0, 0, 6, 8, 2, 0],
],
};
assert_eq!(got, want);
}
}