adds solve_one

This commit is contained in:
2019-02-12 14:15:27 +01:00
parent 8801596de7
commit 1e91d98581
2 changed files with 47 additions and 13 deletions

View File

@@ -144,6 +144,39 @@ impl<'a,V, K: Eq + Hash + Clone> Problem<'a, V, K> {
}; };
solutions solutions
} }
pub fn solve_one(&mut self) -> Option<Variables<'a,V,K>>
where V: Clone + fmt::Debug,
K: Clone + fmt::Debug,
{
let mut stack: Vec<Assignment<'a, V, K>> = vec![];
stack.append(&mut self._push_updates().unwrap());
loop {
let node = stack.pop();
if node.is_none() {
return None;
};
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;
},
};
}
}
} }
pub struct ProblemBuilder<'a, V, K>(Problem<'a, V, K>); pub struct ProblemBuilder<'a, V, K>(Problem<'a, V, K>);

View File

@@ -103,9 +103,7 @@ mod api {
let mut problem = problem let mut problem = problem
.add_constraint(|_| true) .add_constraint(|_| true)
.finish(); .finish();
let results = problem.solve_all(); if let Some(one_result) = problem.solve_one() {
let one_result = results.first().unwrap();
Json(TemplateObject { Json(TemplateObject {
items: one_result items: one_result
.into_iter() .into_iter()
@@ -116,6 +114,9 @@ mod api {
}}) }})
.collect(), .collect(),
}) })
} else {
panic!("No solution at all !");
}
} }
} }