diff options
Diffstat (limited to 'src/jrummikub/ai/fdsolver/constraint/ComparatorConstraint.java')
-rw-r--r-- | src/jrummikub/ai/fdsolver/constraint/ComparatorConstraint.java | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/src/jrummikub/ai/fdsolver/constraint/ComparatorConstraint.java b/src/jrummikub/ai/fdsolver/constraint/ComparatorConstraint.java new file mode 100644 index 0000000..24e7ecf --- /dev/null +++ b/src/jrummikub/ai/fdsolver/constraint/ComparatorConstraint.java @@ -0,0 +1,67 @@ +package jrummikub.ai.fdsolver.constraint; + +import static jrummikub.ai.fdsolver.Satisfiability.*; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; + +import jrummikub.ai.fdsolver.Constraint; +import jrummikub.ai.fdsolver.Propagator; +import jrummikub.ai.fdsolver.Satisfiability; +import jrummikub.ai.fdsolver.Var; + +public class ComparatorConstraint<T> implements Constraint { + Var<T> x, y; + Comparator<T> comparator, reverseComparator; + ComparatorPropagator<T> trueX, trueY, falseX, falseY; + boolean allowEqual; + + ComparatorConstraint(final Comparator<T> comparator, boolean allowEqual, Var<T> x, Var<T> y) { + this.x = x; + this.y = y; + this.comparator = comparator; + this.allowEqual = allowEqual; + reverseComparator = new Comparator<T>() { + @Override + public int compare(T o1, T o2) { + return comparator.compare(o2, o1); + } + }; + trueX = new ComparatorPropagator<T>(comparator, allowEqual, x, y); + trueY = new ComparatorPropagator<T>(reverseComparator, allowEqual, y, x); + falseX = new ComparatorPropagator<T>(reverseComparator, !allowEqual, x, y); + falseY = new ComparatorPropagator<T>(comparator, !allowEqual, y, x); + } + + @Override + public Collection<Var<?>> getWatchedVars() { + return Arrays.<Var<?>>asList(x,y); + } + + @Override + public Collection<Propagator> getPropagators(boolean negate) { + if (negate) { + return Arrays.<Propagator>asList(falseX,falseY); + } else { + return Arrays.<Propagator>asList(trueX,trueY); + } + } + + @Override + public Satisfiability getSatisfiability() { + T maxX = Collections.max(x.getRange(), comparator); + T minY = Collections.min(y.getRange(), comparator); + if (comparator.compare(maxX, minY) < (allowEqual ? 1 : 0)) { + return TAUT; + } + T minX = Collections.min(x.getRange(), comparator); + T maxY = Collections.max(y.getRange(), comparator); + if (comparator.compare(maxY, minX) < (allowEqual ? 0 : 1)) { + return UNSAT; + } + return SAT; + } + +} |