Skip to main content

constraint_search/rule/
intersection.rs

1//! [`GroupIntersection`]: reasoning across two overlapping all-different groups (Sudoku's
2//! locked candidates).
3
4use alloc::vec::Vec;
5
6use super::subset::{collect_groups, is_permutation};
7use crate::{Domain, Domains, Inconsistent, Rule, Var};
8
9/// A value that group `A` must use, and can only take inside its overlap with group `B`, is
10/// used by that overlap, so the rest of `B` cannot take it.
11///
12/// Sudoku players call this *locked candidates*: *pointing* (a block's candidates for a digit
13/// lie in one row) and *claiming* or *box/line reduction* (a row's candidates lie in one
14/// block). The default name is "group intersection"; [`GroupIntersection::with_name`] sets a
15/// domain's own term. It applies to any pair of all-different
16/// groups that share at least two variables, such as irregular regions or extra diagonals.
17/// Like [`ValueSubset`](crate::ValueSubset), it only reasons from groups whose values must
18/// all be used.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct GroupIntersection {
21    /// The rule's [`Rule::cost`].
22    cost: u32,
23    /// The all-different groups.
24    groups: Vec<Vec<Var>>,
25    /// The rule's [`Rule::name`].
26    name: &'static str,
27    /// The ordered pairs `(a, b)` of indices into [`GroupIntersection::groups`] whose groups share
28    /// at least two variables.
29    pairs: Vec<(usize, usize)>,
30}
31
32impl GroupIntersection {
33    /// The intersection rule over `groups`, costing `cost`.
34    #[must_use]
35    pub fn new<G: IntoIterator<Item = Var>>(
36        cost: u32,
37        groups: impl IntoIterator<Item = G>,
38    ) -> Self {
39        let groups = collect_groups(groups);
40        let mut pairs = Vec::new();
41        for (a, first) in groups.iter().enumerate() {
42            for (b, second) in groups.iter().enumerate() {
43                let shared = first.iter().filter(|var| second.contains(var)).count();
44                if a != b && shared >= 2 {
45                    pairs.push((a, b));
46                }
47            }
48        }
49
50        Self {
51            cost,
52            groups,
53            name: "group intersection",
54            pairs,
55        }
56    }
57
58    /// Names the rule in a domain's own terms, such as "pointing pair" for Sudoku.
59    #[must_use]
60    pub fn with_name(mut self, name: &'static str) -> Self {
61        self.name = name;
62        self
63    }
64
65    /// Removes from `outer \ inner` every value that `inner` must use but can only take in
66    /// the variables it shares with `outer`.
67    fn lock<D: Domain>(
68        inner: &[Var],
69        outer: &[Var],
70        domains: &mut Domains<D>,
71    ) -> Result<(), Inconsistent> {
72        if !is_permutation(inner, domains) {
73            return Ok(());
74        }
75
76        let union = domains.union_of(inner);
77        for value in union.values() {
78            let confined = inner
79                .iter()
80                .filter(|&&var| domains[var].contains(value))
81                .all(|var| outer.contains(var));
82            if !confined {
83                continue;
84            }
85
86            for &var in outer.iter().filter(|var| !inner.contains(var)) {
87                domains.remove(var, value)?;
88            }
89        }
90
91        Ok(())
92    }
93}
94
95impl<D: Domain> Rule<D> for GroupIntersection {
96    fn name(&self) -> &str {
97        self.name
98    }
99
100    fn cost(&self) -> u32 {
101        self.cost
102    }
103
104    fn apply(&self, domains: &mut Domains<D>) -> Result<(), Inconsistent> {
105        self.pairs
106            .iter()
107            .try_for_each(|&(a, b)| Self::lock(&self.groups[a], &self.groups[b], domains))
108    }
109}
110
111/// Unit tests for [`GroupIntersection`].
112#[cfg(test)]
113mod tests {
114    use alloc::vec;
115    use alloc::vec::Vec;
116
117    use super::GroupIntersection;
118    use crate::{Domains, Rule, Var};
119
120    /// A box of four cells whose value 3 sits only in its top row removes 3 from the rest of
121    /// that row.
122    #[test]
123    fn pointing() {
124        let mut domains = Domains::<u16>::new();
125        let cells: Vec<Var> = [0b1111, 0b1111, 0b0111, 0b0111, 0b1111, 0b1111]
126            .into_iter()
127            .map(|domain| domains.add(domain))
128            .collect();
129        let block = vec![cells[0], cells[1], cells[2], cells[3]];
130        let row = vec![cells[0], cells[1], cells[4], cells[5]];
131
132        GroupIntersection::new(0, [block, row])
133            .apply(&mut domains)
134            .unwrap();
135
136        assert_eq!(domains[cells[4]], 0b0111);
137        assert_eq!(domains[cells[5]], 0b0111);
138        assert_eq!(domains[cells[0]], 0b1111);
139    }
140
141    /// Groups sharing a single variable form no pair: that case is a hidden single.
142    #[test]
143    fn single_overlap_is_ignored() {
144        let rule = GroupIntersection::new(
145            0,
146            [
147                vec![Var::new(0), Var::new(1)],
148                vec![Var::new(1), Var::new(2)],
149            ],
150        );
151        assert_eq!(rule.pairs, []);
152        assert_eq!(Rule::<u16>::name(&rule), "group intersection");
153    }
154}