use std::fmt::Display;
use crate::axis::Axis;
use bit_set::BitSet;
#[derive(Debug)]
pub struct Table {
pub columns: Vec<Axis>,
pub rows: Vec<Axis>,
pub ncorrect: usize,
pub num_of_axis: usize,
}
impl Display for Table {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, " ")?;
for column in self.columns.iter() {
write!(f, "{}", column)?;
}
writeln!(f, "")?;
for row in self.rows.iter() {
writeln!(f, "{}: {:?}", row, row.state)?;
}
Ok(())
}
}
impl Table {
pub fn new(num_columns: usize, num_rows: usize, filled: usize) -> Self {
let mut rng = rand::rng();
let filled = rand::seq::index::sample(&mut rng, num_rows * num_columns, filled)
.into_iter()
.collect::<Vec<usize>>();
let mut columns: Vec<BitSet> = vec![BitSet::new(); num_columns];
let mut rows: Vec<BitSet> = vec![BitSet::new(); num_rows];
for x in filled {
columns[x % num_columns].insert(x / num_columns);
rows[x / num_columns].insert(x % num_columns);
}
let mut already_correct = 0;
let columns = columns
.iter()
.map(|bitset| {
let mut axis = Axis::new(&bitset);
if bitset.len() == 0 {
axis.solved = true;
already_correct += 1;
}
axis
})
.collect::<Vec<Axis>>();
let rows = rows
.iter()
.map(|bitset| {
let mut axis = Axis::new(&bitset);
if bitset.len() == 0 {
axis.solved = true;
already_correct += 1;
}
axis
})
.collect::<Vec<Axis>>();
Table {
columns,
rows,
ncorrect: already_correct,
num_of_axis: num_columns + num_rows,
}
}
pub fn toggle_square(&mut self, (x, y): (usize, usize)) {
let column_was_solved = self.columns[x].is_solved();
let row_was_solved = self.rows[y].is_solved();
self.columns[x].toggle_state(y);
self.rows[y].toggle_state(x);
let column_now_solved = self.columns[x].is_solved();
let row_now_solved = self.rows[y].is_solved();
if row_was_solved && !row_now_solved {
self.ncorrect -= 1;
}
if !row_was_solved && row_now_solved {
self.ncorrect += 1
}
if column_was_solved && !column_now_solved {
self.ncorrect -= 1;
}
if !column_was_solved && column_now_solved {
self.ncorrect += 1
}
}
pub fn is_solved(&self) -> bool {
self.ncorrect == self.num_of_axis
}
}