Add convenience functions for equality.

This function takes a LHS and RHS only to give the illusion of an
equality.  It simply subtracts one from the other because our
equations are all in the form: coef_i var_i + constant == 0.
This commit is contained in:
David Wang 2017-03-01 08:04:27 +11:00
parent 7e908457a2
commit 58a2b0b41f
2 changed files with 20 additions and 4 deletions

View File

@ -73,7 +73,6 @@ impl Constraint for Equality {
#[cfg(test)]
mod tests {
use ::Puzzle;
use super::Equality;
#[test]
fn test_contradiction() {
@ -81,7 +80,7 @@ mod tests {
let v0 = puzzle.new_var_with_candidates(&[3]);
let v1 = puzzle.new_var_with_candidates(&[0,1]);
puzzle.add_constraint(Box::new(Equality::new(v0 + 2 * v1 - 4)));
puzzle.equals(v0 + 2 * v1, 4);
let search = puzzle.step();
assert!(search.is_none());
@ -93,7 +92,7 @@ mod tests {
let v0 = puzzle.new_var_with_candidates(&[1]);
let v1 = puzzle.new_var_with_candidates(&[1,2,3]);
puzzle.add_constraint(Box::new(Equality::new(v0 + v1 - 4)));
puzzle.equals(v0 + v1, 4);
let search = puzzle.step().expect("contradiction");
assert_eq!(search[v0], 1);

View File

@ -8,7 +8,7 @@ use std::ops::Index;
use std::rc::Rc;
use bit_set::BitSet;
use ::{Constraint,Solution,Val,VarToken};
use ::{Constraint,LinExpr,Solution,Val,VarToken};
use constraint;
/// A collection of candidates.
@ -314,6 +314,23 @@ impl Puzzle {
self.add_constraint(Box::new(constraint::AllDifferent::new(vars)));
}
/// Add an Equality constraint.
///
/// # Examples
///
/// ```
/// let mut magic_square = puzzle_solver::Puzzle::new();
/// let vars = magic_square.new_vars_with_candidates_2d(3, 3,
/// &[1,2,3,4,5,6,7,8,9]);
///
/// magic_square.equals(vars[0][0] + vars[0][1] + vars[0][2], 15);
/// ```
pub fn equals<L,R>(&mut self, lhs: L, rhs: R)
where L: Into<LinExpr>, R: Into<LinExpr> {
self.add_constraint(Box::new(constraint::Equality::new(
lhs.into() - rhs.into())));
}
/// Find any solution to the given puzzle.
///
/// # Examples