constraint_search/table.rs
1//! [`Table`]: a constraint given by its allowed tuples.
2
3use alloc::vec::Vec;
4
5use crate::{Domain, Domains, Inconsistent, Propagator, Var};
6
7/// The variables take one of the listed tuples of values.
8///
9/// Any relation over a few variables can be written this way: a KenKen cage (every tuple
10/// with the right sum or product), the allowed colour pairs of two regions, the shifts a
11/// worker can take on consecutive days. Propagation is complete: afterwards every value left
12/// is part of an allowed tuple whose other values are all still possible. Each run scans the
13/// tuples once.
14///
15/// # Examples
16///
17/// ```
18/// use constraint_search::{Domain, Domains, Propagator, Table};
19///
20/// let mut domains = Domains::<u16>::new();
21/// let x = domains.add(u16::range(4));
22/// let y = domains.add(u16::range(4));
23///
24/// // A two-cell cage whose values sum to 5.
25/// let cage = Table::new([x, y], [[2, 3], [3, 2]]);
26/// cage.propagate(&mut domains, &mut Vec::new())?;
27/// assert!(domains[x].values().eq([2, 3]));
28/// # Ok::<(), constraint_search::Inconsistent>(())
29/// ```
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct Table {
32 /// The constrained variables. Never holds a variable twice.
33 vars: Vec<Var>,
34 /// The allowed tuples back to back, each `vars.len()` values long.
35 tuples: Vec<u32>,
36}
37
38impl Table {
39 /// The constraint that `vars` take one of `tuples`, each listing one value per variable.
40 ///
41 /// # Panics
42 ///
43 /// Panics if `vars` is empty, holds a variable twice, or if a tuple's length differs from
44 /// the number of variables.
45 #[must_use]
46 pub fn new<T: AsRef<[u32]>>(
47 vars: impl IntoIterator<Item = Var>,
48 tuples: impl IntoIterator<Item = T>,
49 ) -> Self {
50 let vars: Vec<Var> = vars.into_iter().collect();
51 assert!(!vars.is_empty(), "a table needs at least one variable");
52
53 crate::assert_distinct(&vars, "a table lists a variable twice");
54
55 let mut flat = Vec::new();
56 for tuple in tuples {
57 let tuple = tuple.as_ref();
58 assert_eq!(
59 tuple.len(),
60 vars.len(),
61 "a tuple needs one value per variable"
62 );
63 flat.extend_from_slice(tuple);
64 }
65
66 Self { vars, tuples: flat }
67 }
68
69 /// The allowed tuples.
70 pub fn tuples(&self) -> impl Iterator<Item = &[u32]> {
71 self.tuples.chunks_exact(self.vars.len())
72 }
73}
74
75impl<D: Domain> Propagator<D> for Table {
76 /// The values seen in a possible tuple, per variable.
77 type Scratch = Vec<D>;
78
79 fn scope(&self) -> &[Var] {
80 &self.vars
81 }
82
83 fn propagate(
84 &self,
85 domains: &mut Domains<D>,
86 supported: &mut Vec<D>,
87 ) -> Result<(), Inconsistent> {
88 supported.clear();
89 supported.resize(self.vars.len(), D::empty());
90 let possible = self.tuples().filter(|tuple| {
91 self.vars
92 .iter()
93 .zip(*tuple)
94 .all(|(&var, &value)| domains[var].contains(value))
95 });
96 for tuple in possible {
97 for (support, &value) in supported.iter_mut().zip(tuple) {
98 support.insert(value);
99 }
100 }
101
102 for (&var, &support) in self.vars.iter().zip(supported.iter()) {
103 domains.restrict(var, support)?;
104 }
105
106 Ok(())
107 }
108}
109
110/// Tests [`Table`] against brute-force enumeration.
111#[cfg(test)]
112mod tests {
113 use alloc::vec::Vec;
114
115 use super::Table;
116 use crate::testing::{Rng, check_against_brute_force};
117
118 /// On random small instances with random tuples, propagation keeps exactly the values
119 /// with a support.
120 #[test]
121 fn matches_brute_force() {
122 let mut rng = Rng::new(11);
123 for _ in 0..2000 {
124 let vars = 1 + rng.below(4);
125 let tuples: Vec<Vec<u32>> = (0..rng.below(12))
126 .map(|_| {
127 (0..vars)
128 .map(|_| u32::try_from(rng.below(5)).unwrap())
129 .collect()
130 })
131 .collect();
132 let allowed = |assignment: &[u32]| tuples.iter().any(|tuple| tuple == assignment);
133
134 check_against_brute_force(&mut rng, vars, 5, allowed, |scope| {
135 Table::new(scope, &tuples)
136 });
137 }
138 }
139}