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 OffsetConstraint extends Constraint { private Var x, y; int offset; Propagator propX, propY; public OffsetConstraint(int offset, Var x, Var y) { this.offset = offset; this.x = x; this.y = y; propX = new OffsetProp(offset, x, y); propY = new OffsetProp(-offset, y, x); } @Override public Collection> getWatchedVars() { return Arrays.> asList(x, y); } private class OffsetProp implements Propagator { private Var x, y; private int offset; public OffsetProp(int offset, Var x, Var y) { this.offset = offset; this.x = x; this.y = y; } @Override public Collection> getWatchedVars() { return Arrays.>asList(y); } @Override public void propagate() { for(Iterator i = x.iterator(); i.hasNext();) { if(!y.getRange().contains(i.next() + offset)) { i.remove(); } } } } @Override public Collection getPropagators(boolean negate) { return Arrays.asList(propX, propY); } @Override public Satisfiability getSatisfiability() { HashSet shiftedRange = new HashSet(); for (int val : x.getRange()) { shiftedRange.add(val + offset); } shiftedRange.retainAll(y.getRange()); if (shiftedRange.isEmpty()) { return Satisfiability.UNSAT; } else if (x.getRange().size() == 1 && y.getRange().size() == 1) { return Satisfiability.TAUT; } else { return Satisfiability.SAT; } } }