Skip to main content

constraint_search/
linear.rs

1//! [`Linear`]: a weighted sum of variables compared with a constant.
2
3use alloc::vec::Vec;
4
5use crate::{Domain, Domains, Inconsistent, Propagator, Var};
6
7/// How the sum of a [`Linear`] constraint compares with its right-hand side.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9pub enum Relation {
10    /// The sum is at most the right-hand side.
11    AtMost,
12    /// The sum equals the right-hand side.
13    Equal,
14    /// The sum is at least the right-hand side.
15    AtLeast,
16}
17
18/// `a₁·x₁ + a₂·x₂ + … (≤ | = | ≥) b`, where each value is read as the integer it is.
19///
20/// This covers Kakuro and Killer-Sudoku cages (sums of digits), Minesweeper (how many of
21/// the neighbouring cells, each 0 or 1, are mines), Battleships row and column counts, card
22/// counts per hand, and cryptarithms such as SEND + MORE = MONEY (one equation with place
23/// values as coefficients).
24///
25/// Propagation reasons on bounds: a value stays only if it can be completed with the smallest
26/// (for `≤`) or largest (for `≥`) contributions the other terms can still make. It fails once
27/// those bounds cannot meet the right-hand side, so a full assignment is always checked. It
28/// is sound but, for `=`, not complete: a value whose completions all fall between the bounds
29/// may stay. Coefficients may be negative; sums are computed in `i128`, so they never
30/// overflow.
31///
32/// # Examples
33///
34/// A Killer-Sudoku cage of two cells summing to 15, digits 1 to 9:
35///
36/// ```
37/// use constraint_search::{Domain, Domains, Linear, Propagator, Relation};
38///
39/// let mut domains = Domains::<u16>::new();
40/// let digits = u16::range(10).difference(u16::singleton(0));
41/// let a = domains.add(digits);
42/// let b = domains.add(digits);
43///
44/// let cage = Linear::sum([a, b], Relation::Equal, 15);
45/// cage.propagate(&mut domains, &mut Vec::new())?;
46/// assert!(domains[a].values().eq(6..=9));
47/// # Ok::<(), constraint_search::Inconsistent>(())
48/// ```
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct Linear {
51    /// The variables, in term order.
52    vars: Vec<Var>,
53    /// The coefficient of each variable, in term order.
54    coefficients: Vec<i64>,
55    /// How the sum compares with [`Linear::rhs`].
56    relation: Relation,
57    /// The right-hand side.
58    rhs: i64,
59}
60
61impl Linear {
62    /// The constraint `Σ coefficient · var (relation) rhs` over the given terms.
63    ///
64    /// A variable may appear in several terms; propagation then treats the terms
65    /// independently, which stays sound.
66    #[must_use]
67    pub fn new(terms: impl IntoIterator<Item = (i64, Var)>, relation: Relation, rhs: i64) -> Self {
68        let (coefficients, vars) = terms.into_iter().unzip();
69
70        Self {
71            vars,
72            coefficients,
73            relation,
74            rhs,
75        }
76    }
77
78    /// The constraint `Σ var (relation) rhs`: every coefficient is 1.
79    #[must_use]
80    pub fn sum(vars: impl IntoIterator<Item = Var>, relation: Relation, rhs: i64) -> Self {
81        Self::new(vars.into_iter().map(|var| (1, var)), relation, rhs)
82    }
83
84    /// The `(coefficient, variable)` terms, in order.
85    pub fn terms(&self) -> impl Iterator<Item = (i64, Var)> + '_ {
86        self.coefficients
87            .iter()
88            .copied()
89            .zip(self.vars.iter().copied())
90    }
91
92    /// How the sum compares with the right-hand side.
93    #[must_use]
94    pub fn relation(&self) -> Relation {
95        self.relation
96    }
97
98    /// The right-hand side.
99    #[must_use]
100    pub fn rhs(&self) -> i64 {
101        self.rhs
102    }
103
104    /// Returns `true` if the sum can stay at most the right-hand side.
105    fn caps(&self) -> bool {
106        matches!(self.relation, Relation::AtMost | Relation::Equal)
107    }
108
109    /// Returns `true` if the sum can reach at least the right-hand side.
110    fn floors(&self) -> bool {
111        matches!(self.relation, Relation::AtLeast | Relation::Equal)
112    }
113}
114
115impl<D: Domain> Propagator<D> for Linear {
116    /// The smallest and largest contribution of each term.
117    type Scratch = Vec<(i128, i128)>;
118
119    fn scope(&self) -> &[Var] {
120        &self.vars
121    }
122
123    fn propagate(
124        &self,
125        domains: &mut Domains<D>,
126        bounds: &mut Vec<(i128, i128)>,
127    ) -> Result<(), Inconsistent> {
128        let rhs = i128::from(self.rhs);
129        let (low, high) = self.term_bounds(domains, bounds);
130        if (self.caps() && low > rhs) || (self.floors() && high < rhs) {
131            return Err(Inconsistent);
132        }
133
134        for (term, (&var, &coefficient)) in self.vars.iter().zip(&self.coefficients).enumerate() {
135            let (term_low, term_high) = bounds[term];
136            let (rest_low, rest_high) = (low - term_low, high - term_high);
137            let mut allowed = domains[var];
138            for value in domains[var].values() {
139                let contribution = i128::from(coefficient) * i128::from(value);
140                let over = self.caps() && contribution + rest_low > rhs;
141                let under = self.floors() && contribution + rest_high < rhs;
142                if over || under {
143                    allowed.remove(value);
144                }
145            }
146
147            domains.restrict(var, allowed)?;
148        }
149
150        Ok(())
151    }
152}
153
154impl Linear {
155    /// Fills `bounds` with each term's smallest and largest contribution over the current
156    /// domains, and returns their sums.
157    fn term_bounds<D: Domain>(
158        &self,
159        domains: &Domains<D>,
160        bounds: &mut Vec<(i128, i128)>,
161    ) -> (i128, i128) {
162        bounds.clear();
163        let (mut low, mut high) = (0, 0);
164        for (&var, &coefficient) in self.vars.iter().zip(&self.coefficients) {
165            let contributions = domains[var]
166                .values()
167                .map(|value| i128::from(coefficient) * i128::from(value));
168            let (term_low, term_high) =
169                contributions.fold((i128::MAX, i128::MIN), |(lo, hi), c| (lo.min(c), hi.max(c)));
170            bounds.push((term_low, term_high));
171            low += term_low;
172            high += term_high;
173        }
174
175        (low, high)
176    }
177}
178
179/// Tests [`Linear`] against brute-force enumeration.
180#[cfg(test)]
181mod tests {
182    use alloc::vec::Vec;
183
184    use super::{Linear, Relation};
185    use crate::testing::{Rng, check_sound_against_brute_force};
186    use crate::{Domains, Inconsistent, Propagator, Var};
187
188    /// On random small instances, propagation keeps every supported value, fails only
189    /// without solutions, and decides full assignments.
190    #[test]
191    fn sound_against_brute_force() {
192        let mut rng = Rng::new(23);
193        for _ in 0..3000 {
194            let vars = 1 + rng.below(4);
195            let coefficients: Vec<i64> = (0..vars)
196                .map(|_| i64::try_from(rng.below(7)).unwrap() - 3)
197                .collect();
198            let relation = [Relation::AtMost, Relation::Equal, Relation::AtLeast][rng.below(3)];
199            let rhs = i64::try_from(rng.below(25)).unwrap() - 8;
200            let holds = |assignment: &[u32]| {
201                let sum: i64 = coefficients
202                    .iter()
203                    .zip(assignment)
204                    .map(|(&a, &x)| a * i64::from(x))
205                    .sum();
206                match relation {
207                    Relation::AtMost => sum <= rhs,
208                    Relation::Equal => sum == rhs,
209                    Relation::AtLeast => sum >= rhs,
210                }
211            };
212
213            check_sound_against_brute_force(&mut rng, vars, 6, holds, |scope: Vec<Var>| {
214                Linear::new(coefficients.iter().copied().zip(scope), relation, rhs)
215            });
216        }
217    }
218
219    /// Bounds that cannot meet the right-hand side fail at once.
220    #[test]
221    fn infeasible_bounds_fail() {
222        let mut domains = Domains::<u16>::new();
223        let x = domains.add(0b11);
224        let y = domains.add(0b11);
225
226        let too_big = Linear::sum([x, y], Relation::AtLeast, 3);
227        assert_eq!(
228            too_big.propagate(&mut domains, &mut Vec::new()),
229            Err(Inconsistent)
230        );
231        let negative = Linear::new([(-1, x), (2, y)], Relation::Equal, 2);
232        negative.propagate(&mut domains, &mut Vec::new()).unwrap();
233        assert_eq!((domains[x], domains[y]), (0b01, 0b10));
234    }
235}