constraint_search/rule.rs
1//! Inference rules: named, costed deductions for human-style solving and difficulty grading.
2//!
3//! Propagators make search fast; rules explain. A [`Rule`] is one technique a person would
4//! use ("naked pair", "X-wing"), with a cost that says how hard it is to spot. [`Rules`] keeps
5//! them ordered by cost and always applies the cheapest one that makes progress, so a solve
6//! reads like a person's, and the most expensive rule it needed grades the puzzle.
7//!
8//! The crate ships rules for all-different groups: [`VariableSubset`], [`ValueSubset`] and
9//! [`GroupIntersection`]. [`PropagatorRule`] turns any propagator into a rule, which covers
10//! sums ([`Linear`](crate::Linear)), nonogram lines ([`Line`](crate::Line)) and tables, and
11//! [`SumDifference`] combines overlapping sums.
12//! Puzzle-specific patterns implement [`Rule`] themselves. [`Trace::why_removed`] answers
13//! "why can `x` not be `v`?" from the steps.
14//!
15//! Rules stay sound when a problem has many solutions, as in card games or under-constrained
16//! puzzles. Only rules with [`Rule::assumes_unique`] need exactly one solution, and they are
17//! off by default.
18
19mod difference;
20mod intersection;
21mod propagated;
22mod subset;
23
24use alloc::boxed::Box;
25use alloc::vec::Vec;
26
27use crate::{Domain, Domains, Inconsistent, Var};
28pub use difference::SumDifference;
29pub use intersection::GroupIntersection;
30pub use propagated::PropagatorRule;
31pub use subset::{ValueSubset, VariableSubset};
32
33/// A named deduction technique with a cost.
34///
35/// Rules are stateless and `Send + Sync`, like [`Propagator`](crate::Propagator)s. Unlike
36/// them, a rule need not catch every consequence; it applies one technique wherever it finds
37/// it.
38pub trait Rule<D: Domain>: Send + Sync {
39 /// The name of the technique, for hints and solve logs.
40 fn name(&self) -> &str;
41
42 /// How hard the technique is to apply; rules run cheapest first. The scale is the
43 /// caller's: grading reports the highest cost a solve needed.
44 fn cost(&self) -> u32;
45
46 /// Returns `true` if the rule is sound only for puzzles with exactly one solution, such as
47 /// Sudoku's unique rectangle. [`Rules`] skips these unless asked to assume uniqueness.
48 fn assumes_unique(&self) -> bool {
49 false
50 }
51
52 /// Applies the technique wherever it finds it, removing values from `domains`.
53 ///
54 /// # Errors
55 ///
56 /// Returns [`Inconsistent`] if a deduction would empty a domain: the puzzle has no
57 /// solution.
58 fn apply(&self, domains: &mut Domains<D>) -> Result<(), Inconsistent>;
59}
60
61/// One application of a rule: which rule, and what it removed.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct Step<D> {
64 /// The rule's position in [`Rules`], for [`Rules::get`].
65 pub rule: usize,
66 /// The rule's [`Rule::cost`].
67 pub cost: u32,
68 /// The values removed from each variable, in the order the variables changed. Never
69 /// empty; each variable appears once.
70 pub removed: Vec<(Var, D)>,
71}
72
73/// The steps of a solve by rules alone, and whether they solved the puzzle.
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct Trace<D> {
76 /// The steps in the order they were applied.
77 pub steps: Vec<Step<D>>,
78 /// `true` if every variable ended with exactly one value.
79 pub solved: bool,
80}
81
82impl<D: Domain> Trace<D> {
83 /// The step that removed `value` from `var`, if one did: the explanation of why `var`
84 /// cannot take `value`. Name the rule with [`Rules::get`] on [`Step::rule`].
85 ///
86 /// # Examples
87 ///
88 /// ```
89 /// use constraint_search::{Domain, Domains, Rules, VariableSubset};
90 ///
91 /// let mut domains = Domains::<u16>::new();
92 /// let x = domains.add(u16::singleton(1));
93 /// let y = domains.add(u16::range(3));
94 ///
95 /// let mut rules = Rules::new();
96 /// rules.add(VariableSubset::new(1, 1, [[x, y]]));
97 /// let trace = rules.solve(&mut domains, false)?;
98 ///
99 /// let step = trace.why_removed(y, 1).expect("1 left y");
100 /// assert_eq!(rules.get(step.rule).name(), "variable single");
101 /// assert!(trace.why_removed(y, 0).is_none());
102 /// # Ok::<(), constraint_search::Inconsistent>(())
103 /// ```
104 #[must_use]
105 pub fn why_removed(&self, var: Var, value: u32) -> Option<&Step<D>> {
106 self.steps.iter().find(|step| {
107 step.removed
108 .iter()
109 .any(|&(removed_var, values)| removed_var == var && values.contains(value))
110 })
111 }
112}
113
114impl<D> Trace<D> {
115 /// The highest cost among the steps, or `None` if the rules could not solve the puzzle.
116 ///
117 /// A puzzle that was solved before any rule ran grades `Some(0)`.
118 #[must_use]
119 pub fn grade(&self) -> Option<u32> {
120 self.solved
121 .then(|| self.steps.iter().map(|step| step.cost).max().unwrap_or(0))
122 }
123}
124
125/// A set of rules, kept in ascending order of cost.
126///
127/// Propagators make search fast; rules explain. [`Rules::step`] applies the cheapest rule
128/// that makes progress, so a solve reads like a person's and each step can serve as a hint.
129/// [`Rules::solve`] repeats that until no rule fires; the most expensive rule it needed
130/// grades the puzzle ([`Trace::grade`]).
131///
132/// ```mermaid
133/// flowchart LR
134/// start([domains]) --> cheapest[try rules, cheapest first]
135/// cheapest -->|a rule removed values| record[record the step] --> cheapest
136/// cheapest -->|no rule fires| done([trace: steps, solved?])
137/// ```
138///
139/// # Examples
140///
141/// ```
142/// use constraint_search::{Domain, Domains, ValueSubset, VariableSubset, Rules};
143///
144/// // One row of four cells over the values 0..4, with two cells already given.
145/// let mut domains = Domains::<u16>::new();
146/// let row: Vec<_> = (0..4).map(|_| domains.add(u16::range(4))).collect();
147/// domains.assign(row[0], 0)?;
148/// domains.assign(row[1], 1)?;
149///
150/// let mut rules = Rules::new();
151/// rules.add(VariableSubset::new(1, 1, [row.clone()]));
152/// rules.add(ValueSubset::new(1, 2, [row.clone()]));
153///
154/// let trace = rules.solve(&mut domains, false)?;
155/// assert!(!trace.solved); // cells 2 and 3 can still swap values 2 and 3
156/// assert_eq!(rules.get(trace.steps[0].rule).name(), "variable single");
157/// # Ok::<(), constraint_search::Inconsistent>(())
158/// ```
159pub struct Rules<D> {
160 /// The rules in ascending order of cost; equal costs keep the order they were added in.
161 rules: Vec<Box<dyn Rule<D>>>,
162}
163
164impl<D: Domain> Rules<D> {
165 /// An empty rule set.
166 #[must_use]
167 pub const fn new() -> Self {
168 Self { rules: Vec::new() }
169 }
170
171 /// Adds `rule` after every rule that costs no more than it.
172 pub fn add(&mut self, rule: impl Rule<D> + 'static) -> &mut Self {
173 let position = self
174 .rules
175 .partition_point(|other| other.cost() <= rule.cost());
176 self.rules.insert(position, Box::new(rule));
177 self
178 }
179
180 /// The rule at `index`, as referenced by [`Step::rule`].
181 ///
182 /// # Panics
183 ///
184 /// Panics if `index` is not below [`Rules::len`].
185 #[must_use]
186 pub fn get(&self, index: usize) -> &dyn Rule<D> {
187 &*self.rules[index]
188 }
189
190 /// The number of rules.
191 #[must_use]
192 pub fn len(&self) -> usize {
193 self.rules.len()
194 }
195
196 /// Returns `true` if the set holds no rule.
197 #[must_use]
198 pub fn is_empty(&self) -> bool {
199 self.rules.is_empty()
200 }
201
202 /// Applies the cheapest rule that removes a value, once; `None` if no rule does.
203 ///
204 /// This is the next hint for a person solving the puzzle. Rules with
205 /// [`Rule::assumes_unique`] take part only if `assume_unique` is `true`.
206 ///
207 /// # Errors
208 ///
209 /// Returns [`Inconsistent`] if a rule finds the puzzle has no solution. Values removed by
210 /// that rule before it failed stay removed.
211 pub fn step(
212 &self,
213 domains: &mut Domains<D>,
214 assume_unique: bool,
215 ) -> Result<Option<Step<D>>, Inconsistent> {
216 for (index, rule) in self.rules.iter().enumerate() {
217 if rule.assumes_unique() && !assume_unique {
218 continue;
219 }
220
221 let mark = domains.trail_len();
222 rule.apply(domains)?;
223 if domains.trail_len() > mark {
224 return Ok(Some(Step {
225 rule: index,
226 cost: rule.cost(),
227 removed: domains.removed_since(mark),
228 }));
229 }
230 }
231
232 Ok(None)
233 }
234
235 /// Applies [`Rules::step`] until no rule makes progress.
236 ///
237 /// # Errors
238 ///
239 /// Returns [`Inconsistent`] if a rule finds the puzzle has no solution.
240 pub fn solve(
241 &self,
242 domains: &mut Domains<D>,
243 assume_unique: bool,
244 ) -> Result<Trace<D>, Inconsistent> {
245 let mut steps = Vec::new();
246 while let Some(step) = self.step(domains, assume_unique)? {
247 steps.push(step);
248 }
249
250 Ok(Trace {
251 steps,
252 solved: domains.is_solved(),
253 })
254 }
255}
256
257impl<D: Domain> Default for Rules<D> {
258 fn default() -> Self {
259 Self::new()
260 }
261}
262
263/// Unit tests for [`Rules`] and [`Trace`].
264#[cfg(test)]
265mod tests {
266 use alloc::vec;
267
268 use super::{Rule, Rules, Step, Trace};
269 use crate::{Domains, Inconsistent, Var};
270
271 /// Removes value 0 from variable 0, costing `.0`, optionally assuming uniqueness.
272 struct DropZero(u32, bool);
273
274 impl Rule<u16> for DropZero {
275 fn name(&self) -> &'static str {
276 "drop zero"
277 }
278
279 fn cost(&self) -> u32 {
280 self.0
281 }
282
283 fn assumes_unique(&self) -> bool {
284 self.1
285 }
286
287 fn apply(&self, domains: &mut Domains<u16>) -> Result<(), Inconsistent> {
288 domains.remove(Var::new(0), 0).map(|_| ())
289 }
290 }
291
292 /// Rules sort by cost, stably, and a step names the cheapest rule that fired.
293 #[test]
294 fn cheapest_rule_fires_first() {
295 let mut rules = Rules::new();
296 rules
297 .add(DropZero(5, false))
298 .add(DropZero(2, false))
299 .add(DropZero(2, true));
300 assert_eq!(rules.get(0).cost(), 2);
301 assert!(!rules.get(0).assumes_unique());
302
303 let mut domains = Domains::<u16>::new();
304 let x = domains.add(0b11);
305 let trace = rules.solve(&mut domains, false).unwrap();
306
307 assert_eq!(
308 trace.steps,
309 vec![Step {
310 rule: 0,
311 cost: 2,
312 removed: vec![(x, 0b01)]
313 }]
314 );
315 assert_eq!(trace.grade(), Some(2));
316 }
317
318 /// A uniqueness rule runs only when asked to assume uniqueness.
319 #[test]
320 fn uniqueness_rules_are_opt_in() {
321 let mut rules = Rules::new();
322 rules.add(DropZero(1, true));
323
324 let mut domains = Domains::<u16>::new();
325 domains.add(0b11);
326 assert_eq!(rules.step(&mut domains, false), Ok(None));
327 assert!(rules.step(&mut domains, true).unwrap().is_some());
328 }
329
330 /// The set reports its size and hands out its rules.
331 #[test]
332 fn sizes() {
333 let mut rules = Rules::<u16>::default();
334 assert!(rules.is_empty());
335
336 rules.add(DropZero(0, false));
337 assert_eq!(rules.len(), 1);
338 assert_eq!(rules.get(0).name(), "drop zero");
339 }
340
341 /// An unsolved trace has no grade; one that needed no step grades zero.
342 #[test]
343 fn grade_needs_a_solve() {
344 let stuck = Trace::<u16> {
345 steps: vec![],
346 solved: false,
347 };
348 let given = Trace::<u16> {
349 steps: vec![],
350 solved: true,
351 };
352 assert_eq!(stuck.grade(), None);
353 assert_eq!(given.grade(), Some(0));
354 }
355}