Skip to content

Instantly share code, notes, and snippets.

@imjacobclark
Created September 2, 2025 21:39
Show Gist options
  • Save imjacobclark/9c38b5eef1565fe42ac4b4f572935044 to your computer and use it in GitHub Desktop.
Save imjacobclark/9c38b5eef1565fe42ac4b4f572935044 to your computer and use it in GitHub Desktop.
bitboard
struct Board {
cells: [u8; 81],
row_mask: [u16; 9],
col_mask: [u16; 9],
box_mask: [u16; 9],
}
impl Board {
fn bit(&self, d: u8) -> u16 {
1 << (d - 1)
}
fn get_box_mask_index(&self, row: usize, col: usize) -> usize {
(row / 3) * 3 + (col / 3)
}
fn get_value_mask_index(&self, row: usize, col: usize) -> usize {
(row * 9) + col
}
fn candidates_mask(&self, row: usize, col: usize) -> u16 {
if(self.cells[self.get_value_mask_index(row, col)] != 0) {
return 0;
}
let b = self.get_box_mask_index(row, col);
self.row_mask[row] & self.col_mask[col] & self.box_mask[b]
}
fn print(&self) {
for r in 0..9 {
if r % 3 == 0 && r != 0 {
println!("------+-------+------");
}
for c in 0..9 {
if c % 3 == 0 && c != 0 {
print!("| ");
}
let v = self.cells[r * 9 + c];
if v == 0 {
print!(". ");
} else {
print!("{} ", v);
}
}
println!();
}
}
fn debug(&self) {
println!("Cells:");
for r in 0..9 {
for c in 0..9 {
let v = self.cells[r * 9 + c];
print!("{:04b} ", v);
}
println!();
}
println!("\nRow masks:");
for r in 0..9 {
println!("row {}: {:09b}", r, self.row_mask[r]);
}
println!("\nCol masks:");
for c in 0..9 {
println!("col {}: {:09b}", c, self.col_mask[c]);
}
println!("\nBox masks:");
for b in 0..9 {
println!("box {}: {:09b}", b, self.box_mask[b]);
}
}
}
fn main() {
let mut board = Board {
cells: [0; 81],
row_mask: [0x1FF; 9],
col_mask: [0x1FF; 9],
box_mask: [0x1FF; 9],
};
let b = board.bit(2);
let box_index = board.get_box_mask_index(0, 0);
let value_index = board.get_value_mask_index(0, 0);
board.cells[value_index] = 2;
board.row_mask[0] &= !b;
board.col_mask[0] &= !b;
board.box_mask[box_index] &= !b;
board.print();
board.debug();
print!("{:09b}", board.candidates_mask(0, 0));
print!("{:09b}", board.candidates_mask(1, 3));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment