summaryrefslogtreecommitdiffstats
path: root/src/jrummikub/ai/fdsolver/Var.java
blob: e023f348a9b332e3fd0d07ebf4ab22da75b43779 (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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package jrummikub.ai.fdsolver;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

public class Var<T> implements Comparable<Var<T>> {
	private Solver solver;
	private HashSet<T> range;
	private HashSet<Constraint> constraints;
	private T recorded;

	public Var(Solver solver, Collection<T> range) {
		this.solver = solver;
		this.range = new HashSet<T>(range);
		constraints = new HashSet<Constraint>();
	}

	public T getValue() {
		if (range.size() != 1)
			return null;
		return range.iterator().next();
	}

	public HashSet<T> getRange() {
		return range;
	}

	void choose(T value) {
		for (Iterator<T> i = this.iterator(); i.hasNext();) {
			if (i.next() != value) {
				i.remove();
			}
		}
	}

	void makeDirty() {
		this.solver.dirtyVars.add(this);
	}

	void invalidate(T value) {
		range.remove(value);
		solver.logInvalidation(this, value);
		makeDirty();
	}
	
	HashSet<Constraint> getConstraints() {
		return constraints;
	}

	public Iterator<T> iterator() {
		final Iterator<T> iterator = range.iterator();
		return new Iterator<T>() {
			T lastValue;

			@Override
			public boolean hasNext() {
				return iterator.hasNext();
			}

			@Override
			public T next() {
				lastValue = iterator.next();
				return lastValue;
			}

			@Override
			public void remove() {
				// TODO logging
				iterator.remove();
				solver.logInvalidation(Var.this, lastValue);
				makeDirty();
				if (range.size() == 0) {
					solver.contradiction = true;
				}
			}
		};
	}
	
	void record() {
		recorded = getValue();
	}
	
	void restore() {
		range.clear();
		range.add(recorded);
	}

	@Override
	public String toString() {
		return "Var" + range;
	}
	
	private int neighborCount() {
		int count = 0;
		for (Constraint constraint : constraints) {
			count += constraint.getWatchedVars().size();
		}
		return count;
	}
	
	@Override
	public int compareTo(Var<T> other) {
		int rangeCompare = ((Integer)range.size()).compareTo(other.range.size());
		if (rangeCompare != 0)
			return rangeCompare;
		return ((Integer)neighborCount()).compareTo(other.neighborCount());
	}

}