Skip to main content

constraint_search/
line.rs

1//! [`Line`]: a row or column of a nonogram (paint-by-numbers) puzzle.
2
3use alloc::vec::Vec;
4
5use crate::{Domain, Domains, Inconsistent, Propagator, Var};
6
7/// The cell value of an empty cell in a [`Line`].
8pub const EMPTY: u32 = 0;
9
10/// The cell value of a filled cell in a [`Line`].
11pub const FILLED: u32 = 1;
12
13/// A line of cells, each [`EMPTY`] (0) or [`FILLED`] (1), holding the given runs of filled
14/// cells in order, separated by at least one empty cell.
15///
16/// Propagation is complete: it considers every placement of the runs that fits the current
17/// domains, and keeps exactly the cell values some placement uses. Values other than 0 and 1
18/// are removed. Each run costs `O(n · k · L)` for `n` cells, `k` runs and the longest run `L`.
19///
20/// # Examples
21///
22/// A line of five cells with runs 3 and 1 has a single placement:
23///
24/// ```
25/// use constraint_search::{Domain, Domains, Line, Propagator};
26///
27/// let mut domains = Domains::<u16>::new();
28/// let cells: Vec<_> = (0..5).map(|_| domains.add(u16::range(2))).collect();
29///
30/// Line::new(cells.iter().copied(), [3, 1]).propagate(&mut domains, &mut Default::default())?;
31/// let picture: Vec<_> = cells.iter().map(|&c| domains.value(c).unwrap()).collect();
32/// assert_eq!(picture, [1, 1, 1, 0, 1]);
33/// # Ok::<(), constraint_search::Inconsistent>(())
34/// ```
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct Line {
37    /// The cells, in order along the line. Never holds a variable twice.
38    cells: Vec<Var>,
39    /// The lengths of the runs of filled cells, in order. Each at least 1.
40    runs: Vec<usize>,
41}
42
43impl Line {
44    /// The line over `cells` holding `runs` filled cells in order.
45    ///
46    /// # Panics
47    ///
48    /// Panics if a run has length 0 or a cell appears twice.
49    #[must_use]
50    pub fn new(
51        cells: impl IntoIterator<Item = Var>,
52        runs: impl IntoIterator<Item = usize>,
53    ) -> Self {
54        let cells: Vec<Var> = cells.into_iter().collect();
55        let runs: Vec<usize> = runs.into_iter().collect();
56        assert!(
57            runs.iter().all(|&run| run > 0),
58            "a run needs at least one cell"
59        );
60
61        crate::assert_distinct(&cells, "a line lists a cell twice");
62
63        Self { cells, runs }
64    }
65
66    /// The number of states per cell position: one per number of runs placed so far.
67    fn width(&self) -> usize {
68        self.runs.len() + 1
69    }
70}
71
72/// Working memory of [`Line`]: reachability of placement states and the values seen.
73#[derive(Debug, Default)]
74pub struct LineScratch {
75    /// `forward[i * w + j]`: the first `i` cells can hold the first `j` runs, with cell `i`
76    /// free to start a run.
77    forward: Vec<bool>,
78    /// `backward[i * w + j]`: from that state, the rest of the line can hold the other runs.
79    backward: Vec<bool>,
80    /// For each cell, whether some placement leaves it empty and whether one fills it.
81    seen: Vec<(bool, bool)>,
82}
83
84impl<D: Domain> Propagator<D> for Line {
85    type Scratch = LineScratch;
86
87    fn scope(&self) -> &[Var] {
88        &self.cells
89    }
90
91    fn propagate(
92        &self,
93        domains: &mut Domains<D>,
94        scratch: &mut LineScratch,
95    ) -> Result<(), Inconsistent> {
96        let open = |cell: usize, value: u32| domains[self.cells[cell]].contains(value);
97        self.reach_forward(&open, &mut scratch.forward);
98        self.reach_backward(&open, &mut scratch.backward);
99        if !scratch.forward[self.cells.len() * self.width() + self.runs.len()] {
100            return Err(Inconsistent);
101        }
102
103        self.collect_support(&open, scratch);
104        for (&cell, &(empty, filled)) in self.cells.iter().zip(&scratch.seen) {
105            let mut allowed = D::empty();
106            if empty {
107                allowed.insert(EMPTY);
108            }
109
110            if filled {
111                allowed.insert(FILLED);
112            }
113
114            domains.restrict(cell, allowed)?;
115        }
116
117        Ok(())
118    }
119}
120
121impl Line {
122    /// The state a run `j` placed from cell `i` leads to, if the cells allow it: past the
123    /// run and the empty cell after it (or at the end of the line).
124    fn place(&self, open: &impl Fn(usize, u32) -> bool, i: usize, j: usize) -> Option<usize> {
125        let end = i + *self.runs.get(j)?;
126        let n = self.cells.len();
127        if end > n || !(i..end).all(|cell| open(cell, FILLED)) {
128            return None;
129        }
130
131        if end == n {
132            Some(n)
133        } else {
134            open(end, EMPTY).then_some(end + 1)
135        }
136    }
137
138    /// Marks the states reachable from the start of the line.
139    fn reach_forward(&self, open: &impl Fn(usize, u32) -> bool, forward: &mut Vec<bool>) {
140        let (n, w) = (self.cells.len(), self.width());
141        forward.clear();
142        forward.resize((n + 1) * w, false);
143        forward[0] = true;
144
145        for i in 0..n {
146            for j in 0..w {
147                if !forward[i * w + j] {
148                    continue;
149                }
150
151                if open(i, EMPTY) {
152                    forward[(i + 1) * w + j] = true;
153                }
154
155                if let Some(next) = self.place(open, i, j) {
156                    forward[next * w + j + 1] = true;
157                }
158            }
159        }
160    }
161
162    /// Marks the states from which the rest of the line can be completed.
163    fn reach_backward(&self, open: &impl Fn(usize, u32) -> bool, backward: &mut Vec<bool>) {
164        let (n, w) = (self.cells.len(), self.width());
165        backward.clear();
166        backward.resize((n + 1) * w, false);
167        backward[n * w + self.runs.len()] = true;
168
169        for i in (0..n).rev() {
170            for j in 0..w {
171                let skip = open(i, EMPTY) && backward[(i + 1) * w + j];
172                let run = self
173                    .place(open, i, j)
174                    .is_some_and(|next| backward[next * w + j + 1]);
175                backward[i * w + j] = skip || run;
176            }
177        }
178    }
179
180    /// Records, per cell, the values used by transitions between reachable states that can
181    /// still complete the line.
182    fn collect_support(&self, open: &impl Fn(usize, u32) -> bool, scratch: &mut LineScratch) {
183        let (n, w) = (self.cells.len(), self.width());
184        scratch.seen.clear();
185        scratch.seen.resize(n, (false, false));
186
187        for i in 0..n {
188            for j in 0..w {
189                if !scratch.forward[i * w + j] {
190                    continue;
191                }
192
193                if open(i, EMPTY) && scratch.backward[(i + 1) * w + j] {
194                    scratch.seen[i].0 = true;
195                }
196
197                let Some(next) = self.place(open, i, j) else {
198                    continue;
199                };
200
201                if scratch.backward[next * w + j + 1] {
202                    let end = i + self.runs[j];
203                    scratch.seen[i..end]
204                        .iter_mut()
205                        .for_each(|cell| cell.1 = true);
206                    if end < n {
207                        scratch.seen[end].0 = true;
208                    }
209                }
210            }
211        }
212    }
213}
214
215/// Tests [`Line`] against brute-force enumeration.
216#[cfg(test)]
217mod tests {
218    use alloc::vec::Vec;
219
220    use super::Line;
221    use crate::testing::{Rng, check_against_brute_force};
222
223    /// The runs of filled cells in `cells`, if every cell is 0 or 1.
224    fn runs_of(cells: &[u32]) -> Option<Vec<usize>> {
225        let mut runs = Vec::new();
226        let mut current = 0;
227        for &cell in cells {
228            match cell {
229                1 => current += 1,
230                0 if current > 0 => {
231                    runs.push(current);
232                    current = 0;
233                }
234                0 => {}
235                _ => return None,
236            }
237        }
238
239        if current > 0 {
240            runs.push(current);
241        }
242
243        Some(runs)
244    }
245
246    /// On random lines and clues, propagation keeps exactly the values some placement uses.
247    #[test]
248    fn matches_brute_force() {
249        let mut rng = Rng::new(31);
250        for _ in 0..3000 {
251            let cells = 1 + rng.below(7);
252            let runs: Vec<usize> = (0..rng.below(3)).map(|_| 1 + rng.below(3)).collect();
253            let holds = |assignment: &[u32]| runs_of(assignment).as_ref() == Some(&runs);
254
255            check_against_brute_force(&mut rng, cells, 3, holds, |scope| {
256                Line::new(scope, runs.clone())
257            });
258        }
259    }
260
261    /// Runs of length zero are rejected.
262    #[test]
263    #[should_panic(expected = "at least one cell")]
264    fn empty_run_panics() {
265        let _ = Line::new([], [0]);
266    }
267}