Refactores solver, removes dead binary code

This commit is contained in:
2019-01-21 21:08:50 +01:00
parent 14f604283c
commit 940927d376
2 changed files with 122 additions and 114 deletions

View File

@@ -1,44 +1,2 @@
//! The weekly menu planner //! The weekly menu planner
//! //!
use cookbook::{Meal, fetch_meals};
use planner::solver::{Variables, Domain, solve_all};
fn generate_weekly_menu() -> String {
let assignments: Variables<Meal> = [
("LundiMidi".to_string(), None), ("LundiSoir".to_string(), None),
("MardiMidi".to_string(), None), ("MardiSoir".to_string(), None),
("MercrediMidi".to_string(), None), ("MercrediSoir".to_string(), None),
].iter().cloned().collect();
let meals: Domain<Meal> = Domain::new(fetch_meals());
let validator = |vars: &Variables<Meal>| {
let mut result = true;
for day in ["Lundi", "Mardi", "Mercredi"].into_iter() {
let all_day = vars.keys().filter(|k| k.starts_with(day));
let mut nutri_value = 0;
for key in all_day {
nutri_value += vars.get(key)
.expect("no value here !")
.expect("no meal there !")
.nutritional_value()
}
println!("{} -> {}", day, nutri_value);
if nutri_value != 1200 { result = false; };
}
println!("Validator returns {}", result);
result
};
let solutions = solve_all(assignments, &meals, validator);
format!("{:#?}", solutions)
}
fn main() {
println!("{}", generate_weekly_menu());
}
#[cfg(test)]
mod tests {
}

View File

@@ -32,20 +32,32 @@ impl<V: fmt::Debug> fmt::Debug for Domain<V> {
} }
} }
type Constraint<'a,V> = fn(&Variables<'a,V>) -> bool;
/// Returns all possible Updates for next assignements, prepended with pub struct Problem<'a, V> {
/// a Clear to ensure the variable is unset before when leaving the branch. /// The initial assignements map
fn assign_next<'a,'b, V>(assign: &'b Variables<'a, V>, domain: &'a Domain<V>) variables: Variables<'a, V>,
-> Option<Vec<Assignment<'a, V>>> /// Each variable has its associated domain
where V: fmt::Debug domains: HashMap<String, &'a Domain<V>>,
{ /// Set of constraints to validate
// Panics on empty domain constraints: Vec<Constraint<'a,V>>,
// If domain values are filtered, then the branch is a dead end }
if domain.values.is_empty() { panic!("No values in domain : {:?}", domain); };
impl<'a,V> Problem<'a, V> {
pub fn build() -> ProblemBuilder<'a,V> {
ProblemBuilder::new()
}
/// Returns all possible Updates for next assignements, prepended with
/// a Clear to ensure the variable is unset before when leaving the branch.
fn _assign_next(&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,_)) = assign.iter().find(|(_, val)| val.is_none()) { if let Some((key,_)) = self.variables.iter().find(|(_, val)| val.is_none()) {
let domain = self.domains.get(key).expect("No domain for variable !");
let mut updates = vec![Assignment::Clear(key.clone())]; let mut updates = vec![Assignment::Clear(key.clone())];
if domain.values.is_empty() { panic!("No value in domain !"); }
// TODO: should be able to filter domain values (inference, pertinence) // TODO: should be able to filter domain values (inference, pertinence)
for value in domain.values.iter() { for value in domain.values.iter() {
updates.push(Assignment::Update(key.clone(), value)); updates.push(Assignment::Update(key.clone(), value));
@@ -54,43 +66,81 @@ fn assign_next<'a,'b, V>(assign: &'b Variables<'a, V>, domain: &'a Domain<V>)
} else { // End of assignements } else { // End of assignements
None None
} }
} }
/// Visit all possible solutions, using a stack. /// Checks that the current assignments doesn't violate any constraint
pub fn solve_all<'a, V>( fn _is_valid(&self) -> bool {
mut assign: Variables<'a, V>, for validator in self.constraints.iter() {
domain: &'a Domain<V>, if validator(&self.variables) == false { return false; }
is_valid: fn(&Variables<'a,V>) -> bool }
) -> Vec<Variables<'a, V>> return true;
}
/// Visit all possible solutions, using a stack.
pub fn solve_all(&mut self) -> Vec<Variables<'a,V>>
where V: Clone + fmt::Debug where V: Clone + fmt::Debug
{ {
let mut solutions: Vec<Variables<V>> = vec![]; let mut solutions: Vec<Variables<V>> = vec![];
let mut stack: Vec<Assignment<'a, V>> = vec![]; let mut stack: Vec<Assignment<'a, V>> = vec![];
stack.append(&mut assign_next(&assign,domain).unwrap()); stack.append(&mut self._assign_next().unwrap());
loop { loop {
let node = stack.pop(); let node = stack.pop();
if node.is_none() { break; }; if node.is_none() { break; };
match node.unwrap() { match node.unwrap() {
Assignment::Update(key, val) => { Assignment::Update(key, val) => {
// Assign the variable and open new branches, if any. // Assign the variable and open new branches, if any.
*assign.get_mut(&key).unwrap() = Some(val); *self.variables.get_mut(&key).unwrap() = Some(val);
// TODO: handle case of empty domain.values // TODO: handle case of empty domain.values
if let Some(mut nodes) = assign_next(&assign, domain) { if let Some(mut nodes) = self._assign_next() {
stack.append(&mut nodes); stack.append(&mut nodes);
} else { } else {
// Assignements are completed // Assignements are completed
if is_valid(&assign) { if self._is_valid() {
solutions.push(assign.clone()); solutions.push(self.variables.clone());
}; };
}; };
}, },
Assignment::Clear(key) => { Assignment::Clear(key) => {
// We are closing this branch, unset the variable // We are closing this branch, unset the variable
*assign.get_mut(&key).unwrap() = None; *self.variables.get_mut(&key).unwrap() = None;
}, },
}; };
}; };
solutions solutions
}
}
pub struct ProblemBuilder<'a, V>(Problem<'a, V>);
impl<'a, V> ProblemBuilder<'a, V> {
fn new() -> ProblemBuilder<'a, V> {
ProblemBuilder(
Problem{
variables: Variables::new(),
domains: HashMap::new(),
constraints: Vec::new(),
})
}
pub fn add_variable(
mut self,
name: String,
domain: &'a Domain<V>,
value: Option<&'a V>,
) -> Self {
self.0.variables.insert(name.clone(), value);
self.0.domains.insert(name, domain);
self
}
pub fn add_constraint(mut self, cons: Constraint<'a,V>) -> Self {
self.0.constraints.push(cons);
self
}
pub fn finish(self) -> Problem<'a, V> {
self.0
}
} }
@@ -99,41 +149,41 @@ mod tests {
#[test] #[test]
fn test_solver_find_pairs() { fn test_solver_find_pairs() {
use super::*; use super::*;
// Find all pairs of two differents
let assign: Variables<i32> = [
("Left".to_string(), None),
("Right".to_string(), None),
].iter().cloned().collect();
let domain = Domain::new(vec![1,2,3]); let domain = Domain::new(vec![1,2,3]);
let constraint = |assign: &Variables<i32>| { let mut problem: Problem<_> = Problem::build()
.add_variable(String::from("Left"), &domain, None)
.add_variable(String::from("Right"), &domain, None)
.add_constraint(
|assign: &Variables<i32>| {
assign.get("Left").unwrap() == assign.get("Right").unwrap() assign.get("Left").unwrap() == assign.get("Right").unwrap()
}; })
.finish();
let solutions: Vec<Variables<i32>> = vec![ let solutions: Vec<Variables<i32>> = vec![
[("Left".to_string(), Some(&3)), ("Right".to_string(), Some(&3)),].iter().cloned().collect(), [("Left".to_string(), Some(&3)), ("Right".to_string(), Some(&3)),].iter().cloned().collect(),
[("Left".to_string(), Some(&2)), ("Right".to_string(), Some(&2)),].iter().cloned().collect(), [("Left".to_string(), Some(&2)), ("Right".to_string(), Some(&2)),].iter().cloned().collect(),
[("Left".to_string(), Some(&1)), ("Right".to_string(), Some(&1)),].iter().cloned().collect(), [("Left".to_string(), Some(&1)), ("Right".to_string(), Some(&1)),].iter().cloned().collect(),
]; ];
assert_eq!(solve_all(assign, &domain, constraint), solutions); assert_eq!(problem.solve_all(), solutions);
} }
#[test] #[test]
fn test_solver_find_pairs_with_initial() { fn test_solver_find_pairs_with_initial() {
use super::*; use super::*;
// Find all pairs of two differents
let assign: Variables<i32> = [
("Left".to_string(), None),
("Right".to_string(), Some(&2)),
].iter().cloned().collect();
let domain = Domain::new(vec![1,2,3]); let domain = Domain::new(vec![1,2,3]);
let constraint = |assign: &Variables<i32>| { let mut problem: Problem<_> = Problem::build()
.add_variable("Left".to_string(), &domain, None)
.add_variable("Right".to_string(), &domain, Some(&2))
.add_constraint( |assign: &Variables<i32>| {
assign.get("Left").unwrap() == assign.get("Right").unwrap() assign.get("Left").unwrap() == assign.get("Right").unwrap()
}; })
.finish();
let solutions: Vec<Variables<i32>> = vec![ let solutions: Vec<Variables<i32>> = vec![
[("Left".to_string(), Some(&2)), ("Right".to_string(), Some(&2)),].iter().cloned().collect(), [("Left".to_string(), Some(&2)), ("Right".to_string(), Some(&2)),].iter().cloned().collect(),
]; ];
assert_eq!(solve_all(assign, &domain, constraint), solutions); assert_eq!(problem.solve_all(), solutions);
} }
} }