Skip to main content

constraint_search/rule/
difference.rs

1//! [`SumDifference`]: subtract one linear equation from another that contains it.
2
3use alloc::vec::Vec;
4
5use crate::{Domain, Domains, Inconsistent, Linear, Propagator, Relation, Rule, Var};
6
7/// When every term of equation `A` also appears in equation `B`, the remaining terms of `B`
8/// sum to `rhs(B) − rhs(A)`.
9///
10/// This is how a person combines overlapping sums: in Minesweeper, a 1 touching cells
11/// `{a, b}` next to a 2 touching `{a, b, c}` makes `c` a mine (the "1-2 pattern"); in Kakuro
12/// and Killer cages, a cage inside a row leaves the rest of the row a known total. Bounds on
13/// each sum alone cannot see this. Only [`Relation::Equal`] constraints take part; the
14/// derived equations are found once, at construction, and propagate like [`Linear`].
15///
16/// The default name is "sum difference"; [`SumDifference::with_name`] sets a domain's own
17/// term.
18///
19/// # Examples
20///
21/// ```
22/// use constraint_search::{Domain, Domains, Linear, Relation, Rules, SumDifference};
23///
24/// let mut domains = Domains::<u16>::new();
25/// let [a, b, c] = [(); 3].map(|()| domains.add(u16::range(2)));
26/// let one = Linear::sum([a, b], Relation::Equal, 1);
27/// let two = Linear::sum([a, b, c], Relation::Equal, 2);
28///
29/// let mut rules = Rules::new();
30/// rules.add(SumDifference::new(2, [one, two]));
31/// rules.solve(&mut domains, false)?;
32/// assert_eq!(domains.value(c), Some(1));
33/// # Ok::<(), constraint_search::Inconsistent>(())
34/// ```
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct SumDifference {
37    /// The rule's [`Rule::cost`].
38    cost: u32,
39    /// The rule's [`Rule::name`].
40    name: &'static str,
41    /// The equations derived by subtracting one given equation from another.
42    derived: Vec<Linear>,
43}
44
45impl SumDifference {
46    /// The rule over `equations`, costing `cost`.
47    #[must_use]
48    pub fn new(cost: u32, equations: impl IntoIterator<Item = Linear>) -> Self {
49        let equations: Vec<Linear> = equations
50            .into_iter()
51            .filter(|equation| equation.relation() == Relation::Equal)
52            .collect();
53        let mut derived = Vec::new();
54        for (i, inner) in equations.iter().enumerate() {
55            for (j, outer) in equations.iter().enumerate() {
56                if i != j {
57                    derived.extend(difference(inner, outer));
58                }
59            }
60        }
61
62        Self {
63            cost,
64            name: "sum difference",
65            derived,
66        }
67    }
68
69    /// Names the rule in a domain's own terms, such as "1-2 pattern" for Minesweeper.
70    #[must_use]
71    pub fn with_name(mut self, name: &'static str) -> Self {
72        self.name = name;
73        self
74    }
75}
76
77/// `outer − inner`, if every term of `inner` appears in `outer` and some term is left over.
78fn difference(inner: &Linear, outer: &Linear) -> Option<Linear> {
79    let mut rest: Vec<(i64, Var)> = outer.terms().collect();
80    for term in inner.terms() {
81        let position = rest.iter().position(|&other| other == term)?;
82        rest.swap_remove(position);
83    }
84
85    (!rest.is_empty()).then(|| Linear::new(rest, Relation::Equal, outer.rhs() - inner.rhs()))
86}
87
88impl<D: Domain> Rule<D> for SumDifference {
89    fn name(&self) -> &str {
90        self.name
91    }
92
93    fn cost(&self) -> u32 {
94        self.cost
95    }
96
97    fn apply(&self, domains: &mut Domains<D>) -> Result<(), Inconsistent> {
98        let mut scratch = Vec::new();
99        self.derived
100            .iter()
101            .try_for_each(|equation| equation.propagate(domains, &mut scratch))
102    }
103}