csp_solver/constraint/
all_different.rs1use crate::domain::Domain;
7use crate::variable::Variable;
8
9use super::traits::{Constraint, Revision, VarId};
10
11#[derive(Debug)]
12pub struct AllDifferent {
13 pub(crate) scope: Vec<VarId>,
14 gac_id: u32,
16}
17
18impl AllDifferent {
19 pub fn new(vars: Vec<VarId>) -> Self {
20 Self {
21 scope: vars,
22 gac_id: crate::solver::gac::next_gac_id(),
23 }
24 }
25
26 pub(crate) fn check_impl<V: PartialEq>(&self, assignment: &[Option<V>]) -> bool {
27 let assigned: Vec<&V> = self
28 .scope
29 .iter()
30 .filter_map(|&v| assignment[v as usize].as_ref())
31 .collect();
32 for i in 0..assigned.len() {
33 for j in (i + 1)..assigned.len() {
34 if assigned[i] == assigned[j] {
35 return false;
36 }
37 }
38 }
39 true
40 }
41
42 pub(crate) fn revise_impl<D: Domain>(&self, vars: &mut [Variable<D>], depth: usize) -> Revision
51 where
52 D::Value: PartialEq + 'static,
53 {
54 let mut changed = false;
55 let singletons: Vec<(VarId, D::Value)> = self
56 .scope
57 .iter()
58 .filter_map(|&v| {
59 vars[v as usize]
60 .domain
61 .singleton_value()
62 .map(|val| (v, val))
63 })
64 .collect();
65
66 for (sv, sval) in &singletons {
67 for &other in &self.scope {
68 if other == *sv {
69 continue;
70 }
71 if vars[other as usize].prune(sval, depth) {
72 changed = true;
73 }
74 if vars[other as usize].domain.is_empty() {
75 return Revision::Unsatisfiable;
76 }
77 }
78 }
79
80 let live = self
82 .scope
83 .iter()
84 .filter(|&&v| {
85 let d = &vars[v as usize].domain;
86 !d.is_singleton() && !d.is_empty()
87 })
88 .count();
89
90 if live >= crate::solver::gac::GAC_MIN_PARTICIPANTS
91 && crate::solver::gac::GAC_IN_ALLDIFF_ENABLED.load(std::sync::atomic::Ordering::Relaxed)
92 {
93 match crate::solver::gac::propagate_gac_core(
94 &self.scope,
95 None,
96 vars,
97 depth,
98 Some(self.gac_id),
99 ) {
100 Revision::Unsatisfiable => return Revision::Unsatisfiable,
101 Revision::Changed => changed = true,
102 Revision::Unchanged => {}
103 }
104 }
105
106 if changed {
107 Revision::Changed
108 } else {
109 Revision::Unchanged
110 }
111 }
112}
113
114impl<D: Domain> Constraint<D> for AllDifferent
115where
116 D::Value: PartialEq + 'static,
117{
118 fn scope(&self) -> &[VarId] {
119 &self.scope
120 }
121 fn check(&self, assignment: &[Option<D::Value>]) -> bool {
122 self.check_impl(assignment)
123 }
124 fn revise(&self, vars: &mut [Variable<D>], depth: usize) -> Revision {
125 self.revise_impl(vars, depth)
126 }
127}