summaryrefslogtreecommitdiffstats
path: root/src/jrummikub/ai/fdsolver/constraint/ComparatorConstraint.java
blob: 24e7ecf70cb3c3034c30895bb4a38690041419f8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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;
	}

}