Skip to main content

constraint_search/rule/
subset.rs

1//! Subset rules over all-different groups: [`VariableSubset`] and [`ValueSubset`], the
2//! Hall-set reasoning a person does by hand (Sudoku calls them naked and hidden subsets).
3
4use alloc::vec::Vec;
5
6use crate::{Domain, Domains, Inconsistent, Rule, Var};
7
8/// `k` variables of an all-different group whose domains together hold only `k` values use
9/// up those values, so no other variable of the group can take them.
10///
11/// Size 1 is a fixed variable whose value leaves the rest of its group. The rule considers
12/// only variables with at most `size` values left, and for sizes above 1 only unfixed ones,
13/// so each size reports its own technique. It is sound for every all-different group,
14/// whether or not the group must use all its values.
15///
16/// Default names are "variable single", "variable pair", "variable triple", "variable quad"
17/// and "variable subset"; [`VariableSubset::with_name`] sets a domain's own term. Sudoku
18/// players call these *naked singles, pairs, triples and quads*; in a logic-grid puzzle it is
19/// "these two people own the only two remaining pets".
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct VariableSubset {
22    /// The number of variables in the subset. At least 1.
23    size: usize,
24    /// The rule's [`Rule::cost`].
25    cost: u32,
26    /// The all-different groups the rule searches.
27    groups: Vec<Vec<Var>>,
28    /// The rule's [`Rule::name`].
29    name: &'static str,
30}
31
32impl VariableSubset {
33    /// The subset rule of `size` variables over `groups`, costing `cost`.
34    ///
35    /// # Panics
36    ///
37    /// Panics if `size` is 0.
38    #[must_use]
39    pub fn new<G: IntoIterator<Item = Var>>(
40        size: usize,
41        cost: u32,
42        groups: impl IntoIterator<Item = G>,
43    ) -> Self {
44        assert!(size > 0, "a subset needs at least one variable");
45
46        let name = [
47            "variable single",
48            "variable pair",
49            "variable triple",
50            "variable quad",
51        ]
52        .get(size - 1)
53        .copied()
54        .unwrap_or("variable subset");
55        Self {
56            size,
57            cost,
58            groups: collect_groups(groups),
59            name,
60        }
61    }
62
63    /// Names the rule in a domain's own terms, such as "naked pair" for Sudoku.
64    #[must_use]
65    pub fn with_name(mut self, name: &'static str) -> Self {
66        self.name = name;
67        self
68    }
69
70    /// Applies the rule to one group.
71    fn apply_to<D: Domain>(
72        &self,
73        group: &[Var],
74        domains: &mut Domains<D>,
75    ) -> Result<(), Inconsistent> {
76        let lengths = if self.size == 1 { 1..=1 } else { 2..=self.size };
77        let candidates: Vec<Var> = group
78            .iter()
79            .copied()
80            .filter(|&var| lengths.contains(&(domains[var].len() as usize)))
81            .collect();
82
83        for_each_combination(candidates.len(), self.size, |chosen| {
84            let in_subset = |var: &Var| chosen.iter().any(|&i| candidates[i] == *var);
85            let values = chosen
86                .iter()
87                .fold(D::empty(), |union, &i| union.union(domains[candidates[i]]));
88            if values.len() as usize != self.size {
89                return Ok(());
90            }
91
92            for &var in group.iter().filter(|var| !in_subset(var)) {
93                domains.remove_all(var, values)?;
94            }
95
96            Ok(())
97        })
98    }
99}
100
101impl<D: Domain> Rule<D> for VariableSubset {
102    fn name(&self) -> &str {
103        self.name
104    }
105
106    fn cost(&self) -> u32 {
107        self.cost
108    }
109
110    fn apply(&self, domains: &mut Domains<D>) -> Result<(), Inconsistent> {
111        self.groups
112            .iter()
113            .try_for_each(|group| self.apply_to(group, domains))
114    }
115}
116
117/// `k` values that only `k` variables of an all-different group can still take must go to
118/// those variables, so those variables can take no other value.
119///
120/// **Only sound where every value must be used:** groups whose variables together can take
121/// exactly as many values as there are variables (a permutation), as in a Sudoku row or a
122/// logic-grid attribute. Other groups are skipped. In `x ∈ {1, 2, 3}, y ∈ {1, 2}` only `x`
123/// can take 3, yet `x = 1, y = 2` is a solution. Card-location and hidden-identity problems
124/// are often not permutations; model them so that they are, or rely on [`VariableSubset`].
125///
126/// Default names are "value single", "value pair", "value triple", "value quad" and "value
127/// subset"; [`ValueSubset::with_name`] sets a domain's own term. Sudoku players call these
128/// *hidden singles, pairs, triples and quads*.
129#[derive(Debug, Clone, PartialEq, Eq)]
130pub struct ValueSubset {
131    /// The number of values in the subset. At least 1.
132    size: usize,
133    /// The rule's [`Rule::cost`].
134    cost: u32,
135    /// The all-different groups the rule searches.
136    groups: Vec<Vec<Var>>,
137    /// The rule's [`Rule::name`].
138    name: &'static str,
139}
140
141impl ValueSubset {
142    /// The subset rule of `size` values over `groups`, costing `cost`.
143    ///
144    /// # Panics
145    ///
146    /// Panics if `size` is 0.
147    #[must_use]
148    pub fn new<G: IntoIterator<Item = Var>>(
149        size: usize,
150        cost: u32,
151        groups: impl IntoIterator<Item = G>,
152    ) -> Self {
153        assert!(size > 0, "a subset needs at least one value");
154
155        let name = ["value single", "value pair", "value triple", "value quad"]
156            .get(size - 1)
157            .copied()
158            .unwrap_or("value subset");
159        Self {
160            size,
161            cost,
162            groups: collect_groups(groups),
163            name,
164        }
165    }
166
167    /// Names the rule in a domain's own terms, such as "hidden pair" for Sudoku.
168    #[must_use]
169    pub fn with_name(mut self, name: &'static str) -> Self {
170        self.name = name;
171        self
172    }
173
174    /// Applies the rule to one group.
175    fn apply_to<D: Domain>(
176        &self,
177        group: &[Var],
178        domains: &mut Domains<D>,
179    ) -> Result<(), Inconsistent> {
180        if !is_permutation(group, domains) {
181            return Ok(());
182        }
183
184        let candidates = self.candidate_values(group, domains);
185        let mut holders: Vec<Var> = Vec::with_capacity(self.size * self.size);
186        for_each_combination(candidates.len(), self.size, |chosen| {
187            let mut values = D::empty();
188            holders.clear();
189            for (value, positions) in chosen.iter().map(|&i| &candidates[i]) {
190                values.insert(*value);
191                for var in positions {
192                    if !holders.contains(var) {
193                        holders.push(*var);
194                    }
195                }
196            }
197
198            if holders.len() != self.size {
199                return Ok(());
200            }
201
202            for &var in &holders {
203                domains.restrict(var, values)?;
204            }
205
206            Ok(())
207        })
208    }
209
210    /// The values of `group` that `1..=size` variables can take, at least one of them unfixed,
211    /// with those variables.
212    fn candidate_values<D: Domain>(
213        &self,
214        group: &[Var],
215        domains: &Domains<D>,
216    ) -> Vec<(u32, Vec<Var>)> {
217        let counts = 1..=self.size;
218        let union = domains.union_of(group);
219
220        union
221            .values()
222            .map(|value| {
223                let holders = group
224                    .iter()
225                    .copied()
226                    .filter(|&var| domains[var].contains(value))
227                    .collect::<Vec<_>>();
228                (value, holders)
229            })
230            .filter(|(_, holders)| counts.contains(&holders.len()))
231            .filter(|(_, holders)| holders.iter().any(|&var| domains[var].len() > 1))
232            .collect()
233    }
234}
235
236impl<D: Domain> Rule<D> for ValueSubset {
237    fn name(&self) -> &str {
238        self.name
239    }
240
241    fn cost(&self) -> u32 {
242        self.cost
243    }
244
245    fn apply(&self, domains: &mut Domains<D>) -> Result<(), Inconsistent> {
246        self.groups
247            .iter()
248            .try_for_each(|group| self.apply_to(group, domains))
249    }
250}
251
252/// Returns `true` if the variables of `group` can together take exactly as many values as
253/// there are variables, so that every value must be used.
254pub(super) fn is_permutation<D: Domain>(group: &[Var], domains: &Domains<D>) -> bool {
255    domains.union_of(group).len() as usize == group.len()
256}
257
258/// Collects the groups of a rule constructor into owned vectors.
259pub(super) fn collect_groups<G: IntoIterator<Item = Var>>(
260    groups: impl IntoIterator<Item = G>,
261) -> Vec<Vec<Var>> {
262    groups
263        .into_iter()
264        .map(|group| group.into_iter().collect())
265        .collect()
266}
267
268/// Calls `visit` with every `k`-element subset of `0..n` as ascending indices, stopping at
269/// the first error.
270fn for_each_combination(
271    n: usize,
272    k: usize,
273    mut visit: impl FnMut(&[usize]) -> Result<(), Inconsistent>,
274) -> Result<(), Inconsistent> {
275    if k > n {
276        return Ok(());
277    }
278
279    let mut chosen: Vec<usize> = (0..k).collect();
280    loop {
281        visit(&chosen)?;
282
283        let Some(last) = (0..k).rev().find(|&i| chosen[i] < n - k + i) else {
284            return Ok(());
285        };
286
287        chosen[last] += 1;
288        for i in last + 1..k {
289            chosen[i] = chosen[i - 1] + 1;
290        }
291    }
292}
293
294/// Unit tests for the subset rules.
295#[cfg(test)]
296mod tests {
297    use alloc::vec;
298    use alloc::vec::Vec;
299
300    use super::{ValueSubset, VariableSubset, for_each_combination};
301    use crate::{Domains, Rule, Var};
302
303    /// A group of variables with the given domains.
304    fn group(domains_of: &[u16]) -> (Domains<u16>, Vec<Var>) {
305        let mut domains = Domains::new();
306        let vars = domains_of
307            .iter()
308            .map(|&domain| domains.add(domain))
309            .collect();
310
311        (domains, vars)
312    }
313
314    /// Combinations come in lexicographic order, and none exist for `k > n`.
315    #[test]
316    fn combinations() {
317        let mut seen = vec![];
318        for_each_combination(4, 2, |chosen| {
319            seen.push((chosen[0], chosen[1]));
320            Ok(())
321        })
322        .unwrap();
323        assert_eq!(seen, [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]);
324
325        for_each_combination(1, 2, |_| panic!("no subset of size 2")).unwrap();
326    }
327
328    /// A variable pair (a naked pair) removes its two values from the rest of the group.
329    #[test]
330    fn naked_pair() {
331        let (mut domains, vars) = group(&[0b0011, 0b0011, 0b0111, 0b1111]);
332        VariableSubset::new(2, 0, [vars.clone()])
333            .apply(&mut domains)
334            .unwrap();
335
336        assert_eq!(domains[vars[2]], 0b0100);
337        assert_eq!(domains[vars[3]], 0b1100);
338    }
339
340    /// A value pair (a hidden pair) strips the other values from its two variables.
341    #[test]
342    fn hidden_pair() {
343        let (mut domains, vars) = group(&[0b1111, 0b1111, 0b1100, 0b1100]);
344        ValueSubset::new(2, 0, [vars.clone()])
345            .apply(&mut domains)
346            .unwrap();
347
348        assert_eq!(domains[vars[0]], 0b0011);
349        assert_eq!(domains[vars[1]], 0b0011);
350    }
351
352    /// A value pair may include a value only one variable can take.
353    #[test]
354    fn hidden_pair_with_a_single() {
355        let (mut domains, vars) = group(&[0b1111, 0b1110, 0b1100, 0b1100]);
356        ValueSubset::new(2, 0, [vars.clone()])
357            .apply(&mut domains)
358            .unwrap();
359
360        assert_eq!(domains[vars[0]], 0b0011);
361        assert_eq!(domains[vars[1]], 0b0010);
362    }
363
364    /// Hidden reasoning leaves groups alone whose values need not all be used.
365    #[test]
366    fn hidden_single_skips_non_permutation() {
367        let (mut domains, vars) = group(&[0b111, 0b011]);
368        ValueSubset::new(1, 0, [vars.clone()])
369            .apply(&mut domains)
370            .unwrap();
371
372        assert_eq!(domains[vars[0]], 0b111);
373    }
374
375    /// Each size reports its own technique name.
376    #[test]
377    fn names() {
378        let variable = [
379            "variable single",
380            "variable pair",
381            "variable triple",
382            "variable quad",
383        ];
384        let value = ["value single", "value pair", "value triple", "value quad"];
385        for (size, (variable, value)) in (1..).zip(variable.into_iter().zip(value)) {
386            let groups = [Vec::<Var>::new()];
387            assert_eq!(
388                Rule::<u16>::name(&VariableSubset::new(size, 0, groups.clone())),
389                variable
390            );
391            assert_eq!(Rule::<u16>::name(&ValueSubset::new(size, 0, groups)), value);
392        }
393
394        let groups = [Vec::<Var>::new()];
395        assert_eq!(
396            Rule::<u16>::name(&ValueSubset::new(5, 0, groups.clone())),
397            "value subset"
398        );
399        let renamed = VariableSubset::new(2, 0, groups).with_name("naked pair");
400        assert_eq!(Rule::<u16>::name(&renamed), "naked pair");
401    }
402}