Struct sudokugen::board::Board

source ·
pub struct Board { /* private fields */ }
Expand description

Represents a sudoku board.

This is usually the entry point to use any of the functionality in this library. You can create a new board by simply calling new and specifying the size of the board.

use sudokugen::{Board, BoardSize};
let board: Board = Board::new(BoardSize::NineByNine);

Or you can parse an existing representation of a board using the from_str method of the FromStr trait.

use sudokugen::board::Board;

let board: Board = "
1 . . | . . . | . . .
. 2 . | . . . | . . .
. . 3 | . . . | . . .
---------------------
. . . | 4 . . | . . .
. . . | . 5 . | . . .
. . . | . . 6 | . . .
---------------------
. . . | . . . | 7 . .
. . . | . . . | . 8 .
. . . | . . . | . . 9
".parse().unwrap();

Implementations§

source§

impl Board

source

pub fn new(board_size: BoardSize) -> Self

Creates a new empty board of the specified size.

use sudokugen::{Board, BoardSize};

let board: Board = Board::new(BoardSize::NineByNine);
source

pub fn board_size(&self) -> BoardSize

Returns the board size of this board..

use sudokugen::{Board, BoardSize};
let board: Board = Board::new(BoardSize::NineByNine);

assert_eq!(board.board_size(), BoardSize::NineByNine);
source

pub fn set(&mut self, loc: &CellLoc, value: u8) -> Option<u8>

Sets the value of a cell in the board using the CellLoc structure abstraction. Returns the previous value in this location.

use sudokugen::{Board, BoardSize};
use sudokugen::board::CellLoc;

let mut board = Board::new(BoardSize::NineByNine);
let cell = CellLoc::at(0, 0, BoardSize::NineByNine);
board.set(&cell, 1);

assert_eq!(board.get(&cell), Some(1));
source

pub fn set_at(&mut self, l: usize, c: usize, value: u8) -> Option<u8>

Convenience method to set a value in the board using line and column indexing. Returns the previous value in the board.

use sudokugen::{Board, BoardSize};

let mut board = Board::new(BoardSize::NineByNine);
board.set_at(0, 0, 1);

assert_eq!(board.get_at(0, 0), Some(1));
source

pub fn unset(&mut self, loc: &CellLoc) -> Option<u8>

Remove a value from the board at this cell and return the previously saved value.

use sudokugen::{Board, BoardSize};    
use sudokugen::board::CellLoc;

let mut board: Board = "1... .... .... ....".parse().unwrap();
let cell = CellLoc::at(0, 0, BoardSize::FourByFour);

let old_value = board.unset(&cell);

assert_eq!(old_value, Some(1));
assert_eq!(board.get(&cell), None);
source

pub fn get(&self, cell: &CellLoc) -> Option<u8>

Returns the value at a cell if there is any or None otherwise.

use sudokugen::board::Board;

let mut board: Board = "1... .... .... ....".parse().unwrap();

assert_eq!(board.get(&board.cell_at(0, 0)), Some(1));
assert_eq!(board.get(&board.cell_at(0, 1)), None);
source

pub fn get_at(&self, l: usize, c: usize) -> Option<u8>

Same as get but more ergonomic for manual usage. Returns the value at that position or None if no value is set. See the method CellLoc::at for an explanation on the arrangement of lines and columns.

use sudokugen::board::Board;

let mut board: Board = "1... .... .... ....".parse().unwrap();

assert_eq!(board.get_at(0, 0), Some(1));
assert_eq!(board.get_at(0, 1), None);
source

pub fn iter_cells(&self) -> impl Iterator<Item = CellLoc>

Return an iterator over all cells in the board.

use sudokugen::{Board, BoardSize};
use sudokugen::board::CellLoc;
use std::collections::BTreeSet;

let board = Board::new(BoardSize::FourByFour);

assert_eq!(
    board.iter_cells().collect::<BTreeSet<CellLoc>>(),
    (0..4).flat_map(|line| (0..4).map(move |col| {
        CellLoc::at(line.clone(), col, BoardSize::FourByFour)
    }))
        .collect::<BTreeSet<CellLoc>>()
);

Keep in mind that this iterates only over the cell location not the cell value, in order to access/modify the current value you’ll need to use the get and set methods of this board.

source

pub fn cell_at(&self, l: usize, c: usize) -> CellLoc

Convenience method to return a CellLoc at this position that is compatible with this board (has the same base_size). See more about referencing cells by line and column using the at method

use sudokugen::{Board, BoardSize};

let board = Board::new(BoardSize::NineByNine);
let cell = board.cell_at(1, 1);

assert_eq!((cell.line(), cell.col()), (1, 1));
source

pub fn rotated(&self) -> Self

Returns a new sudoku Board rotated clockwise by 90deg.

Valid sudoku puzzles are also valid if rotated 90deg, 180deg and 270deg, they are the same puzzle, however must people would have trouble realizing that they are doing the same puzzle. This function provides a cheap way to turn 1 valid puzzle into 4.

use sudokugen::board::Board;

let board: Board = "
1 2 | . .
3 4 | . .
---------
. . | . .
. . | . .
".parse().unwrap();

let rotated_board: Board = "
. . | 3 1
. . | 4 2
---------
. . | . .
. . | . .
".parse().unwrap();

assert_eq!(board.rotated(), rotated_board);
source§

impl Board

source

pub fn generate(board_size: BoardSize) -> Self

Generate a new sudoku board with a unique solution.

This a utility function for generating a new puzzle when you don’t care about the details, it returns a new random board. It’s equivalent to calling Puzzle::generate(base_size).board().clone();.

use sudokugen::{Board, BoardSize};

let board = Board::generate(BoardSize::NineByNine);

println!("{}", board);
source§

impl Board

source

pub fn solve(&mut self) -> Result<(), UnsolvableError>

Solves the sudoku puzzle.

Updates the current board with the solution to that sudoku puzzle.

use sudokugen::board::Board;

let mut board: Board =
    ". . . | 4 . . | 8 7 .
     4 . 3 | . . . | . . .
     2 . . | . . 3 | . . 9
     ---------------------
     . . 6 | 2 . . | . . 7
     . . . | 9 . 6 | . . .
     3 . 9 | . 8 . | . . .
     ---------------------
     . . . | . . . | . 4 .
     8 7 2 | 5 . . | . . .
     . . . | 7 2 . | 6 . .
    "
       .parse()
       .unwrap();

board.solve().unwrap();

assert_eq!(
    board,
    "695412873413879526287653419146235987728946135359187264561398742872564391934721658"
    .parse()
    .unwrap()
);

If the puzzle has no possible solutions, this function returns UnsolvableError.

let mut board: Board = "123. ...4 .... ....".parse().unwrap();
assert!(matches!(board.solve(), Err(UnsolvableError)));

Trait Implementations§

source§

impl Clone for Board

source§

fn clone(&self) -> Board

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Board

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Display for Board

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl FromStr for Board

source§

fn from_str(board_as_string: &str) -> Result<Self, Self::Err>

Parses a board from a string. A board will be parsed from a string with each digit representing a value in the board. Separator characters like space (‘ ’), newline (‘\n’), underscore (‘_’), dash (‘-’), and pipe (‘|’) are ignored to allow a more friendly formatting.

use sudokugen::board::Board;
let board: Board = "
1 . . | . . . | . . .
. 2 . | . . . | . . .
. . 3 | . . . | . . .
---------------------
. . . | 4 . . | . . .
. . . | . 5 . | . . .
. . . | . . 6 | . . .
---------------------
. . . | . . . | 7 . .
. . . | . . . | . 8 .
. . . | . . . | . . 9
".parse().unwrap();

Alternatively a more streamlined format can be used, which is the same but without any formatting characters.

use sudokugen::board::Board;
let board: Board = "123456789........................................................................".parse().unwrap();
§

type Err = MalformedBoardError

The associated error which can be returned from parsing.
source§

impl PartialEq for Board

source§

fn eq(&self, other: &Self) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

§

impl Freeze for Board

§

impl RefUnwindSafe for Board

§

impl Send for Board

§

impl Sync for Board

§

impl Unpin for Board

§

impl UnwindSafe for Board

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

impl<T> Pointable for T

source§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V