diff options
Diffstat (limited to 'src/jrummikub/ai/fdsolver/constraint/SameConstraint.java')
-rw-r--r-- | src/jrummikub/ai/fdsolver/constraint/SameConstraint.java | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/src/jrummikub/ai/fdsolver/constraint/SameConstraint.java b/src/jrummikub/ai/fdsolver/constraint/SameConstraint.java new file mode 100644 index 0000000..7fc8961 --- /dev/null +++ b/src/jrummikub/ai/fdsolver/constraint/SameConstraint.java @@ -0,0 +1,70 @@ +package jrummikub.ai.fdsolver.constraint; + +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; + +import jrummikub.ai.fdsolver.Constraint; +import jrummikub.ai.fdsolver.Propagator; +import jrummikub.ai.fdsolver.Satisfiability; +import jrummikub.ai.fdsolver.Var; + +public class SameConstraint<T> implements Constraint { + private Var<T> x, y; + Propagator propX, propY; + + public SameConstraint(Var<T> x, Var<T> y) { + this.x = x; + this.y = y; + propX = new SameProp<T>(x, y); + propY = new SameProp<T>(y, x); + } + + @Override + public Collection<Var<?>> getWatchedVars() { + return Arrays.<Var<?>> asList(x, y); + } + + private class SameProp<T> implements Propagator { + private Var<T> x, y; + public SameProp(Var<T> x, Var<T> y) { + this.x = x; + this.y = y; + } + + @Override + public Collection<Var<?>> getWatchedVars() { + return Arrays.<Var<?>>asList(y); + } + + @Override + public void propagate() { + for(Iterator<T> i = x.iterator(); i.hasNext();) { + if(!y.getRange().contains(i.next())) { + i.remove(); + } + } + } + } + + + @Override + public Collection<Propagator> getPropagators(boolean negate) { + return Arrays.asList(propX, propY); + } + + @Override + public Satisfiability getSatisfiability() { + HashSet<T> range = new HashSet<T>(x.getRange()); + range.retainAll(y.getRange()); + if (range.isEmpty()) { + return Satisfiability.UNSAT; + } else if (x.getRange().size() == 1 && y.getRange().size() == 1) { + return Satisfiability.TAUT; + } else { + return Satisfiability.SAT; + } + } + +} |