Skip to main content

csp_solver/constraint/
all_different.rs

1//! N-ary all-different constraint.
2//!
3//! Tests: `tests/solver.rs` (live path via `Csp::add_all_different`);
4//! `tests/sudoku.rs`, `tests/futoshiki.rs` exercise the GAC core end-to-end.
5
6use 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    /// Stable per-constraint id keying the GAC matching warm-start cache.
15    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    /// Singleton removal followed by GAC when enough participants remain live.
43    ///
44    /// Singleton removal always runs (it is the only step that detects two
45    /// *assigned* variables sharing a value — GAC skips assigned vars). Above a
46    /// dynamic live-unassigned-count gate, Régin GAC then adds the Hall-set
47    /// pruning arc consistency misses; below it, GAC would find nothing more, so
48    /// it is skipped. The gate is on the *live* count, not the constraint's
49    /// original arity, so deep search nodes with few free variables pay nothing.
50    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        // Dynamic gate: count live (non-singleton, non-empty) variables.
81        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}