|
|
|
@@ -7,11 +7,13 @@ use std::clone::Clone;
|
|
|
|
use std::collections::HashMap;
|
|
|
|
use std::collections::HashMap;
|
|
|
|
|
|
|
|
|
|
|
|
/// An assignments map of variables
|
|
|
|
/// An assignments map of variables
|
|
|
|
pub type Variables<'a, V, K> = HashMap<K, Option<&'a V>>;
|
|
|
|
type Variables<'a, V> = Vec<Option<&'a V>>;
|
|
|
|
|
|
|
|
/// A solution returned by [`Solver`]
|
|
|
|
|
|
|
|
pub type Solution<'a, V, K> = HashMap<K, Option<&'a V>>;
|
|
|
|
|
|
|
|
|
|
|
|
enum Assignment<'a, V, K> {
|
|
|
|
enum Assignment<'a, V> {
|
|
|
|
Update(K, &'a V),
|
|
|
|
Update(usize, &'a V),
|
|
|
|
Clear(K)
|
|
|
|
Clear(usize)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// Collection of references to values owned by a domain.
|
|
|
|
/// Collection of references to values owned by a domain.
|
|
|
|
@@ -99,7 +101,7 @@ impl<V: fmt::Debug> fmt::Debug for Domain<V> {
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
pub type Constraint<'a,V, K> = fn(&Variables<'a,V, K>) -> bool;
|
|
|
|
pub type Constraint<'a,V> = fn(&Variables<'a,V>) -> bool;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/// Could be more efficient to just use fixed array of options as variables,
|
|
|
|
/// Could be more efficient to just use fixed array of options as variables,
|
|
|
|
@@ -108,12 +110,13 @@ pub type Constraint<'a,V, K> = fn(&Variables<'a,V, K>) -> bool;
|
|
|
|
/// It makes sense with an array where indexing is O(1)
|
|
|
|
/// It makes sense with an array where indexing is O(1)
|
|
|
|
|
|
|
|
|
|
|
|
pub struct Problem<'a, V, K> {
|
|
|
|
pub struct Problem<'a, V, K> {
|
|
|
|
|
|
|
|
keys: Vec<K>,
|
|
|
|
/// The initial assignements map
|
|
|
|
/// The initial assignements map
|
|
|
|
variables: Variables<'a, V, K>,
|
|
|
|
variables: Variables<'a, V>,
|
|
|
|
/// Each variable has its associated domain
|
|
|
|
/// Each variable has its associated domain
|
|
|
|
domains: HashMap<K, DomainValues<'a,V>>,
|
|
|
|
domains: Vec<DomainValues<'a,V>>,
|
|
|
|
/// Set of constraints to validate
|
|
|
|
/// Set of constraints to validate
|
|
|
|
constraints: Vec<Constraint<'a,V,K>>,
|
|
|
|
constraints: Vec<Constraint<'a,V>>,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
impl<'a, V, K: Eq + Hash + Clone> Problem<'a, V, K> {
|
|
|
|
impl<'a, V, K: Eq + Hash + Clone> Problem<'a, V, K> {
|
|
|
|
@@ -123,14 +126,14 @@ impl<'a, V, K: Eq + Hash + Clone> Problem<'a, V, K> {
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
pub fn from_template() -> Problem<'a, V, K> {
|
|
|
|
pub fn from_template() -> Problem<'a, V, K> {
|
|
|
|
let mut builder = Self::build();
|
|
|
|
let builder = Self::build();
|
|
|
|
|
|
|
|
|
|
|
|
builder.finish()
|
|
|
|
builder.finish()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// Returns all possible Updates for next assignements, prepended with
|
|
|
|
/// Returns all possible Updates for next assignements, prepended with
|
|
|
|
/// a Clear to ensure the variable is unset before when leaving the branch.
|
|
|
|
/// a Clear to ensure the variable is unset before when leaving the branch.
|
|
|
|
fn _push_updates(&self) -> Option<Vec<Assignment<'a,V, K>>> {
|
|
|
|
fn _push_updates(&self) -> Option<Vec<Assignment<'a,V>>> {
|
|
|
|
// TODO: should be able to inject a choosing strategy
|
|
|
|
// TODO: should be able to inject a choosing strategy
|
|
|
|
if let Some(key) = self._next_assign() {
|
|
|
|
if let Some(key) = self._next_assign() {
|
|
|
|
let domain_values = self.domains
|
|
|
|
let domain_values = self.domains
|
|
|
|
@@ -142,10 +145,7 @@ impl<'a, V, K: Eq + Hash + Clone> Problem<'a, V, K> {
|
|
|
|
// TODO: should be able to filter domain values (inference, pertinence)
|
|
|
|
// TODO: should be able to filter domain values (inference, pertinence)
|
|
|
|
domain_values.iter().for_each(|value| {
|
|
|
|
domain_values.iter().for_each(|value| {
|
|
|
|
updates.push(
|
|
|
|
updates.push(
|
|
|
|
Assignment::Update(
|
|
|
|
Assignment::Update(key, *value)
|
|
|
|
key.clone(),
|
|
|
|
|
|
|
|
*value
|
|
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
);
|
|
|
|
);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
Some(updates)
|
|
|
|
Some(updates)
|
|
|
|
@@ -154,11 +154,11 @@ impl<'a, V, K: Eq + Hash + Clone> Problem<'a, V, K> {
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
fn _next_assign(&self) -> Option<&K> {
|
|
|
|
fn _next_assign(&self) -> Option<usize> {
|
|
|
|
self.variables
|
|
|
|
self.variables.iter()
|
|
|
|
.iter()
|
|
|
|
.enumerate()
|
|
|
|
.find_map(|(key, val)| {
|
|
|
|
.find_map(|(idx, val)| {
|
|
|
|
if val.is_none() { Some(key) }
|
|
|
|
if val.is_none() { Some(idx) }
|
|
|
|
else { None }
|
|
|
|
else { None }
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
@@ -171,13 +171,9 @@ impl<'a, V, K: Eq + Hash + Clone> Problem<'a, V, K> {
|
|
|
|
return true;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// Returns all complete solutions, after visiting all possible outcomes using a stack (DFS).
|
|
|
|
fn _solve(&mut self, limit: Option<usize>) -> Vec<Solution<'a, V, K>> {
|
|
|
|
pub fn solve_all(&mut self) -> Vec<Variables<'a,V,K>>
|
|
|
|
let mut solutions: Vec<Solution<V, K>> = vec![];
|
|
|
|
where V: Clone + fmt::Debug,
|
|
|
|
let mut stack: Vec<Assignment<'a, V>> = vec![];
|
|
|
|
K: Clone + fmt::Debug,
|
|
|
|
|
|
|
|
{
|
|
|
|
|
|
|
|
let mut solutions: Vec<Variables<V, K>> = vec![];
|
|
|
|
|
|
|
|
let mut stack: Vec<Assignment<'a, V, K>> = vec![];
|
|
|
|
|
|
|
|
if let Some(mut init_updates) = self._push_updates() {
|
|
|
|
if let Some(mut init_updates) = self._push_updates() {
|
|
|
|
stack.append(&mut init_updates);
|
|
|
|
stack.append(&mut init_updates);
|
|
|
|
} else {
|
|
|
|
} else {
|
|
|
|
@@ -187,66 +183,56 @@ impl<'a, V, K: Eq + Hash + Clone> Problem<'a, V, K> {
|
|
|
|
|
|
|
|
|
|
|
|
loop {
|
|
|
|
loop {
|
|
|
|
let node = stack.pop();
|
|
|
|
let node = stack.pop();
|
|
|
|
|
|
|
|
// There is no more combination to try out
|
|
|
|
if node.is_none() { break; };
|
|
|
|
if node.is_none() { break; };
|
|
|
|
|
|
|
|
// Exit early if we have enough solutions
|
|
|
|
|
|
|
|
if limit.is_some()
|
|
|
|
|
|
|
|
&& solutions.len() == limit.unwrap()
|
|
|
|
|
|
|
|
{
|
|
|
|
|
|
|
|
break;
|
|
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
match node.unwrap() {
|
|
|
|
match node.unwrap() {
|
|
|
|
Assignment::Update(key, val) => {
|
|
|
|
Assignment::Update(idx, val) => {
|
|
|
|
// Assign the variable and open new branches, if any.
|
|
|
|
// Assign the variable and open new branches, if any.
|
|
|
|
*self.variables.get_mut(&key).unwrap() = Some(val);
|
|
|
|
self.variables[idx] = Some(val);
|
|
|
|
// TODO: handle case of empty domain.values
|
|
|
|
// TODO: handle case of empty domain.values
|
|
|
|
if let Some(mut nodes) = self._push_updates() {
|
|
|
|
if let Some(mut nodes) = self._push_updates() {
|
|
|
|
stack.append(&mut nodes);
|
|
|
|
stack.append(&mut nodes);
|
|
|
|
} else {
|
|
|
|
} else {
|
|
|
|
// Assignements are completed
|
|
|
|
// Assignements are completed
|
|
|
|
if self._is_valid() {
|
|
|
|
if self._is_valid() {
|
|
|
|
solutions.push(self.variables.clone());
|
|
|
|
solutions.push(
|
|
|
|
|
|
|
|
// Builds Solution
|
|
|
|
|
|
|
|
self.keys.iter().cloned()
|
|
|
|
|
|
|
|
.zip(self.variables.iter().cloned())
|
|
|
|
|
|
|
|
.collect()
|
|
|
|
|
|
|
|
);
|
|
|
|
};
|
|
|
|
};
|
|
|
|
};
|
|
|
|
};
|
|
|
|
},
|
|
|
|
},
|
|
|
|
Assignment::Clear(key) => {
|
|
|
|
Assignment::Clear(idx) => {
|
|
|
|
// We are closing this branch, unset the variable
|
|
|
|
// We are closing this branch, unset the variable
|
|
|
|
*self.variables.get_mut(&key).unwrap() = None;
|
|
|
|
self.variables[idx] = None;
|
|
|
|
},
|
|
|
|
},
|
|
|
|
};
|
|
|
|
};
|
|
|
|
};
|
|
|
|
};
|
|
|
|
solutions
|
|
|
|
solutions
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
pub fn solve_one(&mut self) -> Option<Variables<'a,V,K>>
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns all complete solutions, after visiting all possible outcomes using a stack (DFS).
|
|
|
|
|
|
|
|
pub fn solve_all(&mut self) -> Vec<Solution<'a,V,K>>
|
|
|
|
where V: Clone + fmt::Debug,
|
|
|
|
where V: Clone + fmt::Debug,
|
|
|
|
K: Clone + fmt::Debug,
|
|
|
|
K: Clone + fmt::Debug,
|
|
|
|
{
|
|
|
|
{
|
|
|
|
let mut stack: Vec<Assignment<'a, V, K>> = vec![];
|
|
|
|
self._solve(None) // No limit
|
|
|
|
if let Some(mut init_updates) = self._push_updates() {
|
|
|
|
|
|
|
|
stack.append(&mut init_updates);
|
|
|
|
|
|
|
|
} else {
|
|
|
|
|
|
|
|
panic!("Could not initialize !");
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
loop {
|
|
|
|
pub fn solve_one(&mut self) -> Option<Solution<'a,V,K>>
|
|
|
|
let node = stack.pop();
|
|
|
|
where V: Clone + fmt::Debug,
|
|
|
|
if node.is_none() {
|
|
|
|
K: Clone + fmt::Debug,
|
|
|
|
return None;
|
|
|
|
{
|
|
|
|
};
|
|
|
|
self._solve(Some(1)).pop()
|
|
|
|
match node.unwrap() {
|
|
|
|
|
|
|
|
Assignment::Update(key, val) => {
|
|
|
|
|
|
|
|
// Assign the variable and open new branches, if any.
|
|
|
|
|
|
|
|
*self.variables.get_mut(&key).unwrap() = Some(val);
|
|
|
|
|
|
|
|
// TODO: handle case of empty domain.values
|
|
|
|
|
|
|
|
if let Some(mut nodes) = self._push_updates() {
|
|
|
|
|
|
|
|
stack.append(&mut nodes);
|
|
|
|
|
|
|
|
} else {
|
|
|
|
|
|
|
|
// Assignements are completed
|
|
|
|
|
|
|
|
if self._is_valid() {
|
|
|
|
|
|
|
|
return Some(self.variables.clone());
|
|
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
},
|
|
|
|
|
|
|
|
Assignment::Clear(key) => {
|
|
|
|
|
|
|
|
// We are closing this branch, unset the variable
|
|
|
|
|
|
|
|
*self.variables.get_mut(&key).unwrap() = None;
|
|
|
|
|
|
|
|
},
|
|
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
@@ -256,20 +242,22 @@ impl<'a, V, K: Eq + Hash + Clone> ProblemBuilder<'a, V, K> {
|
|
|
|
fn new() -> ProblemBuilder<'a, V, K> {
|
|
|
|
fn new() -> ProblemBuilder<'a, V, K> {
|
|
|
|
ProblemBuilder(
|
|
|
|
ProblemBuilder(
|
|
|
|
Problem{
|
|
|
|
Problem{
|
|
|
|
|
|
|
|
keys: Vec::new(),
|
|
|
|
variables: Variables::new(),
|
|
|
|
variables: Variables::new(),
|
|
|
|
domains: HashMap::new(),
|
|
|
|
domains: Vec::new(),
|
|
|
|
constraints: Vec::new(),
|
|
|
|
constraints: Vec::new(),
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
pub fn add_variable(mut self, name: K, domain: Vec<&'a V>, value: Option<&'a V>) -> Self
|
|
|
|
pub fn add_variable(mut self, name: K, domain: Vec<&'a V>, value: Option<&'a V>) -> Self
|
|
|
|
{
|
|
|
|
{
|
|
|
|
self.0.variables.insert(name.clone(), value);
|
|
|
|
self.0.keys.push(name);
|
|
|
|
self.0.domains.insert(name, domain);
|
|
|
|
self.0.variables.push(value);
|
|
|
|
|
|
|
|
self.0.domains.push(domain);
|
|
|
|
self
|
|
|
|
self
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
pub fn add_constraint(mut self, cons: Constraint<'a,V, K>) -> Self {
|
|
|
|
pub fn add_constraint(mut self, cons: Constraint<'a,V>) -> Self {
|
|
|
|
self.0.constraints.push(cons);
|
|
|
|
self.0.constraints.push(cons);
|
|
|
|
self
|
|
|
|
self
|
|
|
|
}
|
|
|
|
}
|
|
|
|
@@ -289,15 +277,15 @@ mod tests {
|
|
|
|
let mut problem: Problem<_, _> = Problem::build()
|
|
|
|
let mut problem: Problem<_, _> = Problem::build()
|
|
|
|
.add_variable(String::from("Left"), domain.all(), None)
|
|
|
|
.add_variable(String::from("Left"), domain.all(), None)
|
|
|
|
.add_variable(String::from("Right"), domain.all(), None)
|
|
|
|
.add_variable(String::from("Right"), domain.all(), None)
|
|
|
|
.add_constraint(|assign: &Variables<i32, _>| {
|
|
|
|
.add_constraint(|assign: &Variables<i32>| {
|
|
|
|
assign.get("Left").unwrap() == assign.get("Right").unwrap()
|
|
|
|
assign[0] == assign[1]
|
|
|
|
})
|
|
|
|
})
|
|
|
|
.finish();
|
|
|
|
.finish();
|
|
|
|
|
|
|
|
|
|
|
|
let solutions: Vec<Variables<i32, _>> = vec![
|
|
|
|
let solutions: Vec<Solution<i32, _>> = vec![
|
|
|
|
[("Left".to_string(), Some(&3)), ("Right".to_string(), Some(&3)),].iter().cloned().collect(),
|
|
|
|
[(String::from("Left"), Some(&3)), (String::from("Right"), Some(&3))].iter().cloned().collect(),
|
|
|
|
[("Left".to_string(), Some(&2)), ("Right".to_string(), Some(&2)),].iter().cloned().collect(),
|
|
|
|
[(String::from("Left"), Some(&2)), (String::from("Right"), Some(&2))].iter().cloned().collect(),
|
|
|
|
[("Left".to_string(), Some(&1)), ("Right".to_string(), Some(&1)),].iter().cloned().collect(),
|
|
|
|
[(String::from("Left"), Some(&1)), (String::from("Right"), Some(&1))].iter().cloned().collect(),
|
|
|
|
];
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
|
|
assert_eq!(problem.solve_all(), solutions);
|
|
|
|
assert_eq!(problem.solve_all(), solutions);
|
|
|
|
@@ -310,13 +298,13 @@ mod tests {
|
|
|
|
let mut problem: Problem<_, _> = Problem::build()
|
|
|
|
let mut problem: Problem<_, _> = Problem::build()
|
|
|
|
.add_variable("Left".to_string(), domain.all(), None)
|
|
|
|
.add_variable("Left".to_string(), domain.all(), None)
|
|
|
|
.add_variable("Right".to_string(), domain.all(), Some(&2))
|
|
|
|
.add_variable("Right".to_string(), domain.all(), Some(&2))
|
|
|
|
.add_constraint( |assign: &Variables<i32, _>| {
|
|
|
|
.add_constraint( |assign: &Variables<i32>| {
|
|
|
|
assign.get("Left").unwrap() == assign.get("Right").unwrap()
|
|
|
|
assign[0] == assign[1]
|
|
|
|
})
|
|
|
|
})
|
|
|
|
.finish();
|
|
|
|
.finish();
|
|
|
|
|
|
|
|
|
|
|
|
let solutions: Vec<Variables<i32, _>> = vec![
|
|
|
|
let solutions: Vec<Solution<i32, String>> = vec![
|
|
|
|
[("Left".to_string(), Some(&2)), ("Right".to_string(), Some(&2)),].iter().cloned().collect(),
|
|
|
|
[(String::from("Left"), Some(&2)), (String::from("Right"), Some(&2))].iter().cloned().collect(),
|
|
|
|
];
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
|
|
assert_eq!(problem.solve_all(), solutions);
|
|
|
|
assert_eq!(problem.solve_all(), solutions);
|
|
|
|
|