picrs-lib 0.1.0

library providing basic functionality of a picross game
Documentation
use std::fmt::Display;

use bit_set::BitSet;

#[derive(Debug)]
pub struct Axis {
    pub hints: Vec<usize>,
    pub state: BitSet,
    pub solved: bool,
}
impl Display for Axis {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[")?;
        for hint in self.hints.iter() {
            write!(f, "{}", hint)?;
            write!(f, ",")?;
        }
        write!(f, "]")?;
        Ok(())
    }
}
impl Axis {
    pub fn new(filled_squares: &BitSet) -> Self {
        Axis {
            hints: Axis::calculate_groups(filled_squares),
            state: BitSet::new(),
            solved: Default::default(),
        }
    }
    pub fn toggle_state(&mut self, index: usize) {
        if self.state.contains(index) {
            self.state.remove(index);
        } else {
            self.state.insert(index);
        }
        self.solved = self.is_solved();
    }
    pub fn is_solved(&self) -> bool {
        if Axis::calculate_groups(&self.state) == self.hints {
            true
        } else {
            false
        }
    }
    fn calculate_groups(filled_squares: &BitSet) -> Vec<usize> {
        if filled_squares.is_empty() {
            return vec![0];
        }

        let mut sorted: Vec<usize> = filled_squares.iter().collect();
        sorted.sort_unstable();
        let mut count = 1;
        let mut hints = Vec::new();

        for i in 1..sorted.len() {
            if sorted[i] == sorted[i - 1] + 1 {
                count += 1;
            } else {
                hints.push(count);
                count = 1;
            }
        }
        if count > 0 {
            hints.push(count);
        }
        hints
    }
}