1 Commits

Author SHA1 Message Date
3ccc6b4659 row col block as different datasets.
unexpectedly this seems to be slower for now... :(
2022-07-18 16:07:07 +02:00

View File

@ -1,124 +1,61 @@
use std::time::Instant; use std::time::Instant;
#[derive(Copy, Clone, Debug)]
struct Bitset {
set: u16,
}
impl Bitset {
pub fn new() -> Self {
Self { set: 0 }
}
#[inline(always)]
fn get(&self, nr: usize) -> bool {
self.set & (1 << nr) != 0
}
#[inline(always)]
fn set(&mut self, nr: usize) {
self.set |= 1 << nr;
}
#[inline(always)]
fn unset(&mut self, nr: usize) {
self.set &= !(1 << nr);
}
}
const BLOCK_SIZE: usize = 4;
//const MAX_BLOCK_SIZE: usize = 10;
struct SField { struct SField {
field: Vec<usize>, field: Vec<usize>,
rows: Vec<Vec<usize>>,
cols: Vec<Vec<usize>>,
blocks: Vec<Vec<usize>>,
fixed: Vec<usize>, fixed: Vec<usize>,
size: usize, size: usize,
block_size: usize,
pos: usize, pos: usize,
pos_last_placed: usize, pos_last_placed: usize,
num_fields: usize, num_fields: usize,
possible_values: Vec<Vec<usize>>, possible_values: Vec<Vec<usize>>,
// For each row/col/block we create a bitset that represents the numbers
// that are already in that row, col or block.
// This way we can check very fast if a nr fits into a specific field or not.
rows: [Bitset; BLOCK_SIZE * BLOCK_SIZE],
cols: [Bitset; BLOCK_SIZE * BLOCK_SIZE],
blocks: [Bitset; BLOCK_SIZE * BLOCK_SIZE],
}
#[inline(always)]
fn xy_to_pos(x: usize, y: usize, size: usize) -> usize {
y * size + x
}
#[inline(always)]
fn pos_to_xy_blocknr(pos: usize, size: usize) -> (usize, usize, usize) {
let x = pos % size;
let y = pos / size;
let block_x = x / BLOCK_SIZE;
let block_y = y / BLOCK_SIZE;
let block_nr = block_y * BLOCK_SIZE + block_x;
(x, y, block_nr)
} }
impl SField { impl SField {
pub fn new() -> SField { pub fn new(block_size: usize) -> SField {
const SIZE: usize = BLOCK_SIZE * BLOCK_SIZE; let size = block_size * block_size;
// EMPTY FIELD // EMPTY FIELD
// let field = vec![0; size * size]; // let field = vec![0; size * size];
#[rustfmt::skip] // BLOCK_SIZE 4
let field = match BLOCK_SIZE {
4 => vec![
0usize,15,0,0,0,0,11,4,0,5,0,0,0,0,12,8,
12,0,0,9,0,1,0,5,0,0,8,15,0,0,0,13,
0,0,3,0,0,10,13,0,0,11,4,0,15,0,6,0,
13,10,0,11,0,0,0,14,0,3,2,0,0,9,0,0,
0,0,15,10,8,0,0,0,0,0,14,0,0,6,2,0,
0,0,14,0,0,0,6,0,0,0,0,0,1,0,0,0,
0,11,0,8,3,0,15,1,6,0,0,0,0,0,0,7,
0,6,0,7,0,0,0,0,8,13,0,0,10,0,0,0,
0,14,0,2,0,0,0,0,3,0,5,0,11,15,9,0,
0,0,0,12,11,0,2,0,0,0,0,0,0,0,0,0,
0,8,0,0,6,14,1,0,13,15,0,0,0,0,0,10,
10,0,0,3,9,0,7,0,0,1,0,0,13,12,8,0,
7,0,0,0,0,0,14,0,0,0,0,0,0,0,0,9,
0,3,0,14,0,0,9,6,0,0,0,0,0,4,0,0,
0,4,6,0,0,7,0,0,0,0,0,0,0,0,0,0,
5,2,0,0,0,4,10,15,1,0,3,0,0,0,7,0,
],
3 => vec![
0,0,0,0,0,0,0,0,9,
0,0,0,0,8,9,0,2,0,
0,0,0,0,2,0,4,0,0,
0,0,4,0,6,0,0,0,8,
0,0,0,5,0,0,0,0,0,
0,6,5,0,0,2,0,7,4,
0,3,0,0,0,5,0,4,0,
0,0,1,8,0,0,0,0,0,
0,0,8,2,0,0,0,6,0,
],
_ => panic!("Unsupported block size. Only 3 and 4 is ok for now.")
};
// MANY SOLUTIONS
// #[rustfmt::skip] // #[rustfmt::skip]
// let field = vec![ // let field = vec![
// 0,0,0,0,0,0,0,0,9, // 0,15,0,0,0,0,11,4,0,5,0,0,0,0,12,8,
// 0,0,0,0,8,9,0,2,0, // 12,0,0,9,0,1,0,5,0,0,8,15,0,0,0,13,
// 0,0,0,0,2,0,4,0,0, // 0,0,3,0,0,10,13,0,0,11,4,0,15,0,6,0,
// 0,0,4,0,6,0,0,0,8, // 13,10,0,11,0,0,0,14,0,3,2,0,0,9,0,0,
// 0,0,0,5,0,0,0,0,0, // 0,0,15,10,8,0,0,0,0,0,14,0,0,6,2,0,
// 0,6,5,0,0,2,0,7,4, // 0,0,14,0,0,0,6,0,0,0,0,0,1,0,0,0,
// 0,3,0,0,0,5,0,4,0, // 0,11,0,8,3,0,15,1,6,0,0,0,0,0,0,7,
// 0,0,1,8,0,0,0,0,0, // 0,6,0,7,0,0,0,0,8,13,0,0,10,0,0,0,
// 0,0,8,2,0,0,0,6,0, // 0,14,0,2,0,0,0,0,3,0,5,0,11,15,9,0,
// 0,0,0,12,11,0,2,0,0,0,0,0,0,0,0,0,
// 0,8,0,0,6,14,1,0,13,15,0,0,0,0,0,10,
// 10,0,0,3,9,0,7,0,0,1,0,0,13,12,8,0,
// 7,0,0,0,0,0,14,0,0,0,0,0,0,0,0,9,
// 0,3,0,14,0,0,9,6,0,0,0,0,0,4,0,0,
// 0,4,6,0,0,7,0,0,0,0,0,0,0,0,0,0,
// 5,2,0,0,0,4,10,15,1,0,3,0,0,0,7,0,
// ]; // ];
// MANY SOLUTIONS
#[rustfmt::skip]
let field = vec![
0,0,0,0,0,0,0,0,9,
0,0,0,0,8,9,0,2,0,
0,0,0,0,2,0,4,0,0,
0,0,4,0,6,0,0,0,8,
0,0,0,5,0,0,0,0,0,
0,6,5,0,0,2,0,7,4,
0,3,0,0,0,5,0,4,0,
0,0,1,8,0,0,0,0,0,
0,0,8,2,0,0,0,6,0,
];
// HARD // HARD
// #[rustfmt::skip] // #[rustfmt::skip]
// let field = vec![ // let field = vec![
@ -147,7 +84,7 @@ impl SField {
// 7,3,6,0,2,0,0,0,0, // 7,3,6,0,2,0,0,0,0,
// ]; // ];
let mut fixed = Vec::with_capacity(SIZE * SIZE); let mut fixed = Vec::with_capacity(size * size);
field.iter().for_each(|e| { field.iter().for_each(|e| {
if *e == 0 { if *e == 0 {
fixed.push(0); fixed.push(0);
@ -156,85 +93,70 @@ impl SField {
} }
}); });
// create bitsets let rows = SField::rows_from_plain_field(&field);
// rows let cols = SField::cols_from_plain_field(&field);
let mut bit_rows = [Bitset::new(); SIZE]; let blocks = SField::blocks_from_plain_field(&field);
for row_nr in 0..SIZE {
let mut row = [0; SIZE];
for count in 0..SIZE {
row[count] = field[xy_to_pos(count, row_nr, SIZE)];
}
row.into_iter()
.filter(|val| *val != 0)
.for_each(|val| bit_rows[row_nr].set(val - 1));
}
// cols
let mut bit_cols = [Bitset::new(); SIZE];
for col_nr in 0..SIZE {
let mut col = [0; SIZE];
for count in 0..SIZE {
col[count] = field[xy_to_pos(col_nr, count, SIZE)];
}
col.into_iter()
.filter(|val| *val != 0)
.for_each(|val| bit_cols[col_nr].set(val - 1));
}
// blocks
let mut bit_blocks = [Bitset::new(); SIZE];
for block_nr in 0..SIZE {
let block_start_x = block_nr * BLOCK_SIZE % SIZE;
let block_start_y = block_nr * BLOCK_SIZE / SIZE * BLOCK_SIZE;
let mut block = [0; SIZE];
for count in 0..SIZE {
let block_offset_x = count % BLOCK_SIZE;
let block_offset_y = count / BLOCK_SIZE;
let field_x = block_start_x + block_offset_x;
let field_y = block_start_y + block_offset_y;
//dbg!(
//block_nr,
//block_start_x,
//block_start_y,
//block_offset_x,
//block_offset_y,
//field_x,
//field_y,
//);
block[count] = field[xy_to_pos(field_x, field_y, SIZE)];
}
block
.into_iter()
.filter(|x| *x != 0)
.for_each(|x| bit_blocks[block_nr].set(x - 1));
}
//dbg!(bit_rows);
//dbg!(bit_cols);
//dbg!(bit_blocks);
SField { SField {
field, field,
rows,
cols,
blocks,
fixed, fixed,
size: SIZE, size,
block_size,
pos: 0, pos: 0,
pos_last_placed: 0, pos_last_placed: 0,
num_fields: SIZE * SIZE, num_fields: size * size,
possible_values: vec![vec![]; SIZE * SIZE], possible_values: vec![vec![]; size * size],
rows: bit_rows,
cols: bit_cols,
blocks: bit_blocks,
} }
} }
fn rows_from_plain_field(field: &[usize]) -> Vec<Vec<usize>> {
let mut rows = vec![vec![0; 9]; 9];
for row in 0..9 {
for col in 0..9 {
rows[row][col] = field[row * 9 + col];
}
}
rows
}
fn cols_from_plain_field(field: &[usize]) -> Vec<Vec<usize>> {
let mut cols = vec![vec![0; 9]; 9];
for row in 0..9 {
for col in 0..9 {
cols[col][row] = field[row * 9 + col];
}
}
cols
}
fn blocks_from_plain_field(field: &[usize]) -> Vec<Vec<usize>> {
fn get_block_with_pos(field: &[usize], pos: usize) -> Vec<usize> {
let block_start_row = pos / 9 / 3 * 3;
let block_start_col = pos % 9 / 3 * 3;
let mut block = vec![];
for r in 0..3 {
for c in 0..3 {
block.push(field[9 * (block_start_row + r) + block_start_col + c])
}
}
block
}
let mut blocks = vec![];
let block_start_positions = [0, 3, 6, 27, 30, 33, 54, 57, 60];
for pos in block_start_positions {
blocks.push(get_block_with_pos(field, pos));
}
blocks
}
fn build_possible_values_db(&mut self) { fn build_possible_values_db(&mut self) {
for idx in 0..self.num_fields { for idx in 0..self.num_fields {
if self.fixed[idx] == 1 { if self.fixed[idx] == 1 {
@ -257,29 +179,24 @@ impl SField {
let mut found_solution = false; let mut found_solution = false;
let mut num_solutions = 0; let mut num_solutions = 0;
let mut loop_count = 0; //let mut loop_count = 0;
let mut last_loop_count = 0;
let mut now = Instant::now();
loop { loop {
//std::thread::sleep_ms(30); //std::thread::sleep_ms(30);
//self.print_clear(); //self.print_clear();
//self.print(); //self.print();
loop_count += 1; //loop_count += 1;
if now.elapsed().as_millis() >= 1000 { //if loop_count % 1000000 == 0 {
now = Instant::now(); //self.print_clear();
self.print_clear(); //self.print();
self.print(); //}
println!("{} loops/s", loop_count - last_loop_count);
last_loop_count = loop_count;
}
if self.is_end() { if self.is_end() {
found_solution = true; found_solution = true;
num_solutions += 1; num_solutions += 1;
//if num_solutions % 100 == 0 { if num_solutions % 100 == 0 {
//self.print_clear(); self.print_clear();
//println!("Solutions: {}", num_solutions); println!("Solutions: {}", num_solutions);
//self.print(); self.print();
//} }
if self.is_fixed() { if self.is_fixed() {
continue; continue;
@ -423,9 +340,8 @@ impl SField {
continue; continue;
} }
let nr = *nr; if self.ok(*nr) {
if self.ok(nr) { self.set(*nr);
self.set(nr);
return true; return true;
} }
} }
@ -439,11 +355,14 @@ impl SField {
#[inline(always)] #[inline(always)]
fn ok(&self, nr: usize) -> bool { fn ok(&self, nr: usize) -> bool {
//self.block_ok(nr) && self.row_ok(nr) && self.col_ok(nr) self.block_ok(nr) && self.row_ok(nr) && self.col_ok(nr)
}
let (x, y, block_nr) = pos_to_xy_blocknr(self.pos, self.size); #[inline(always)]
fn _pos_to_xy(&self) -> (usize, usize) {
!self.rows[y].get(nr - 1) && !self.cols[x].get(nr - 1) && !self.blocks[block_nr].get(nr - 1) let y = self.pos / self.size;
let x = self.pos % self.size;
(x + 1, y + 1)
} }
#[inline(always)] #[inline(always)]
@ -463,82 +382,104 @@ impl SField {
unsafe { *self.field.get_unchecked(pos) } unsafe { *self.field.get_unchecked(pos) }
} }
#[inline(always)]
fn get_x_y_block_blockoffset(&self) -> (usize, usize, usize, usize) {
// TODO:
// this only works for 3x3 sudoku
#[rustfmt::skip]
let block_nrs = [
0, 1, 2, 9,10,11,18,19,20,
3, 4, 5,12,13,14,21,22,23,
6, 7, 8,15,16,17,24,25,26,
27,28,29,36,37,38,45,46,47,
30,31,32,39,40,41,48,49,50,
33,34,35,42,43,44,51,52,53,
54,55,56,63,64,65,72,73,74,
57,58,59,66,67,68,75,76,77,
60,61,62,69,70,71,78,79,80,
];
let y = self.pos / self.size;
let x = self.pos % self.size;
let block_field = unsafe { block_nrs.get_unchecked(self.pos) };
let block_nr = block_field / self.size;
let block_offset = block_field - (block_nr * self.size);
(x, y, block_nr, block_offset)
}
#[inline(always)] #[inline(always)]
fn set(&mut self, nr: usize) { fn set(&mut self, nr: usize) {
let old = unsafe { self.field.get_unchecked_mut(self.pos) }; //assert_eq!(self.field, self.flatten_rows());
//assert_eq!(self.field, self.flatten_cols());
//assert_eq!(self.field, self.flatten_blocks());
// if another number > 0 was in that cell, we need to remove that number from our bitsets self.field[self.pos] = nr;
if *old > 0 {
let (x, y, block_nr) = pos_to_xy_blocknr(self.pos, self.size);
self.rows[y].unset(*old - 1);
self.cols[x].unset(*old - 1);
self.blocks[block_nr].unset(*old - 1);
}
// add new nr to our bitsets if it is a meaningful (> 0) number
if nr > 0 {
let (x, y, block_nr) = pos_to_xy_blocknr(self.pos, self.size);
self.rows[y].set(nr - 1);
self.cols[x].set(nr - 1);
self.blocks[block_nr].set(nr - 1);
}
// write the new number into the field
*old = nr;
// remember the last placed position for debugging purposes
self.pos_last_placed = self.pos; self.pos_last_placed = self.pos;
}
/* // update rows, cols and blocks
#[inline(always)] // this is more expensive than only updating field but should be outweight
fn get_row(&self, row: &mut [usize]) { // by the fact that row_ok(), col_ok() and block_ok() just need to do simple
for (idx, row_elem) in row.iter_mut().enumerate() { // lookups now
*row_elem = self.get_field_at_pos((self.pos / self.size) * self.size + idx);
}
}
#[inline(always)] let (x, y, block_nr, block_offset) = self.get_x_y_block_blockoffset();
fn get_col(&self, col: &mut [usize]) {
for (idx, col_elem) in col.iter_mut().enumerate() {
*col_elem = self.get_field_at_pos(idx * self.size + self.pos % self.size);
}
}
#[inline(always)] //println!("[{},{}] setting {}", y, x, nr);
fn get_block(&self, block: &mut [usize]) {
let block_start_row = self.pos / self.size / self.block_size * self.block_size;
let block_start_col = self.pos % self.size / self.block_size * self.block_size;
for r in 0..self.block_size { let row = unsafe { self.rows.get_unchecked_mut(y) };
for c in 0..self.block_size { let value = unsafe { row.get_unchecked_mut(x) };
block[r * self.block_size + c] = *value = nr;
self.get_field_at_pos(self.size * (block_start_row + r) + block_start_col + c);
} let col = unsafe { self.cols.get_unchecked_mut(x) };
} let value = unsafe { col.get_unchecked_mut(y) };
*value = nr;
let block = unsafe { self.blocks.get_unchecked_mut(block_nr) };
let value = unsafe { block.get_unchecked_mut(block_offset) };
*value = nr;
//assert_eq!(self.field, self.flatten_rows());
//assert_eq!(self.field, self.flatten_cols());
//assert_eq!(self.field, self.flatten_blocks());
} }
#[inline(always)] #[inline(always)]
fn block_ok(&self, nr: usize) -> bool { fn block_ok(&self, nr: usize) -> bool {
let mut block = [0; MAX_BLOCK_SIZE * MAX_BLOCK_SIZE]; // TODO
self.get_block(&mut block[0..self.size]); // works only on 3x3 sudoku
!block.contains(&nr) #[rustfmt::skip]
let block_nrs = [
0,0,0,1,1,1,2,2,2,
0,0,0,1,1,1,2,2,2,
0,0,0,1,1,1,2,2,2,
3,3,3,4,4,4,5,5,5,
3,3,3,4,4,4,5,5,5,
3,3,3,4,4,4,5,5,5,
6,6,6,7,7,7,8,8,8,
6,6,6,7,7,7,8,8,8,
6,6,6,7,7,7,8,8,8,
];
let block_nr = unsafe { block_nrs.get_unchecked(self.pos) };
//println!("Block {}: {:?}", block_nr, self.blocks[*block_nr]);
!unsafe { self.blocks.get_unchecked(*block_nr) }.contains(&nr)
} }
#[inline(always)] #[inline(always)]
fn row_ok(&self, nr: usize) -> bool { fn row_ok(&self, nr: usize) -> bool {
let mut row = [0; MAX_BLOCK_SIZE * MAX_BLOCK_SIZE]; let row_nr = self.pos / self.size;
self.get_row(&mut row[0..self.size]); //println!("{:?}", self.rows[row_nr]);
!row.contains(&nr) !unsafe { self.rows.get_unchecked(row_nr) }.contains(&nr)
} }
#[inline(always)] #[inline(always)]
fn col_ok(&self, nr: usize) -> bool { fn col_ok(&self, nr: usize) -> bool {
let mut col = [0; MAX_BLOCK_SIZE * MAX_BLOCK_SIZE]; let col_nr = self.pos % self.size;
self.get_col(&mut col[0..self.size]); //println!("{:?}", self.cols[col_nr]);
!col.contains(&nr) !unsafe { self.cols.get_unchecked(col_nr) }.contains(&nr)
} }
*/
#[inline(always)] #[inline(always)]
fn next(&mut self) -> bool { fn next(&mut self) -> bool {
@ -546,7 +487,6 @@ impl SField {
return false; return false;
} }
//println!("next {} -> {}", self.pos, self.pos + 1);
self.pos += 1; self.pos += 1;
true true
} }
@ -567,12 +507,53 @@ impl SField {
if !self.solve_backtracking() { if !self.solve_backtracking() {
println!("there is no solution."); println!("there is no solution.");
} }
println!("took {:.3}s", now.elapsed().as_secs_f64()); println!("took {:.3} seconds", now.elapsed().as_secs_f64());
} }
//fn flatten_blocks(&self) -> Vec<usize> {
//#[rustfmt::skip]
//let block_nrs = [
//0, 1, 2, 9,10,11,18,19,20,
//3, 4, 5,12,13,14,21,22,23,
//6, 7, 8,15,16,17,24,25,26,
//27,28,29,36,37,38,45,46,47,
//30,31,32,39,40,41,48,49,50,
//33,34,35,42,43,44,51,52,53,
//54,55,56,63,64,65,72,73,74,
//57,58,59,66,67,68,75,76,77,
//60,61,62,69,70,71,78,79,80,
//];
//let mut flattened = Vec::with_capacity(self.num_fields);
//for (idx, nr) in block_nrs.iter().enumerate() {
//let block_nr = nr / self.size;
//let block_offset = nr - (block_nr * self.size);
//flattened.push(self.blocks[block_nr][block_offset]);
//}
//flattened
//}
//fn flatten_rows(&self) -> Vec<usize> {
//let mut flattened = Vec::with_capacity(self.num_fields);
//for row in self.rows.iter() {
//for val in row {
//flattened.push(*val);
//}
//}
//flattened
//}
//fn flatten_cols(&self) -> Vec<usize> {
//let mut flattened = Vec::with_capacity(self.num_fields);
//for idx in 0..self.num_fields {
//flattened.push(self.cols[idx % self.size][idx / self.size]);
//}
//flattened
//}
} }
fn run() -> Result<(), String> { fn run() -> Result<(), String> {
let mut field = SField::new(); let mut field = SField::new(3);
field.build_possible_values_db(); field.build_possible_values_db();