constraint_search/all_different.rs
1//! [`AllDifferent`]: pairwise distinct values, with full Hall-set reasoning.
2
3mod graph;
4
5use alloc::vec::Vec;
6
7use crate::{Domain, Domains, Inconsistent, Propagator, Var};
8pub use graph::MatchingScratch;
9
10/// The variables take pairwise distinct values.
11///
12/// Propagation is complete (generalised arc consistency, Régin 1994): afterwards every value
13/// left in a domain is part of some assignment of distinct values. This subsumes all Hall-set
14/// reasoning: a fixed value leaves the other domains, `k` variables sharing `k` values keep
15/// those values to themselves, and a value that only one variable can still take goes to it
16/// when the values must all be used. It fails as soon as fewer values than variables remain.
17///
18/// Each run builds a matching between variables and values, in `O(n · e)` for `n` variables
19/// and `e` variable–value pairs. Its buffers live in [`MatchingScratch`] and are reused.
20///
21/// # Examples
22///
23/// ```
24/// use constraint_search::{AllDifferent, Domains, MatchingScratch, Propagator};
25///
26/// let mut domains = Domains::<u16>::new();
27/// let x = domains.add(0b011);
28/// let y = domains.add(0b011);
29/// let z = domains.add(0b111);
30///
31/// // x and y use up the values 0 and 1, so z must be 2.
32/// AllDifferent::new([x, y, z]).propagate(&mut domains, &mut MatchingScratch::default())?;
33/// assert_eq!(domains.value(z), Some(2));
34/// # Ok::<(), constraint_search::Inconsistent>(())
35/// ```
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct AllDifferent {
38 /// The constrained variables. Never holds a variable twice.
39 vars: Vec<Var>,
40}
41
42impl AllDifferent {
43 /// All-different over `vars`.
44 ///
45 /// # Panics
46 ///
47 /// Panics if a variable appears twice.
48 #[must_use]
49 pub fn new(vars: impl IntoIterator<Item = Var>) -> Self {
50 let vars: Vec<Var> = vars.into_iter().collect();
51
52 crate::assert_distinct(&vars, "all-different lists a variable twice");
53
54 Self { vars }
55 }
56}
57
58impl<D: Domain> Propagator<D> for AllDifferent {
59 type Scratch = MatchingScratch;
60
61 fn scope(&self) -> &[Var] {
62 &self.vars
63 }
64
65 fn propagate(
66 &self,
67 domains: &mut Domains<D>,
68 graph: &mut MatchingScratch,
69 ) -> Result<(), Inconsistent> {
70 graph.build(domains, &self.vars);
71 if !graph.match_all() {
72 return Err(Inconsistent);
73 }
74
75 for &(position, value) in graph.unsupported() {
76 domains.remove(self.vars[position], value)?;
77 }
78
79 Ok(())
80 }
81}
82
83/// Tests [`AllDifferent`] against brute-force enumeration.
84#[cfg(test)]
85mod tests {
86 use alloc::vec::Vec;
87
88 use super::{AllDifferent, MatchingScratch};
89 use crate::testing::{Rng, check_against_brute_force};
90 use crate::{Domains, Inconsistent, Propagator};
91
92 /// Is every value of `assignment` different from the others?
93 fn distinct(assignment: &[u32]) -> bool {
94 assignment
95 .iter()
96 .enumerate()
97 .all(|(i, a)| assignment[i + 1..].iter().all(|b| a != b))
98 }
99
100 /// On random small instances, propagation keeps exactly the values with a support.
101 #[test]
102 fn matches_brute_force() {
103 let mut rng = Rng::new(7);
104 for _ in 0..2000 {
105 let vars = 1 + rng.below(5);
106 check_against_brute_force(&mut rng, vars, 6, distinct, AllDifferent::new);
107 }
108 }
109
110 /// A non-permutation keeps a value only one variable can take: it need not be used.
111 #[test]
112 fn unused_values_stay() {
113 let mut domains = Domains::<u16>::new();
114 let x = domains.add(0b111);
115 let y = domains.add(0b011);
116
117 AllDifferent::new([x, y])
118 .propagate(&mut domains, &mut MatchingScratch::default())
119 .unwrap();
120 assert_eq!((domains[x], domains[y]), (0b111, 0b011));
121 }
122
123 /// Three variables over two values fail by pigeonhole before any is fixed.
124 #[test]
125 fn pigeonhole_fails() {
126 let mut domains = Domains::<u16>::new();
127 let vars: Vec<_> = (0..3).map(|_| domains.add(0b11)).collect();
128
129 assert_eq!(
130 AllDifferent::new(vars).propagate(&mut domains, &mut MatchingScratch::default()),
131 Err(Inconsistent)
132 );
133 }
134
135 /// Listing a variable twice is rejected at construction.
136 #[test]
137 #[should_panic(expected = "twice")]
138 fn duplicate_var_panics() {
139 let mut domains = Domains::<u16>::new();
140 let x = domains.add(0b11);
141 let _ = AllDifferent::new([x, x]);
142 }
143}