-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNode.java
108 lines (83 loc) · 2.66 KB
/
Node.java
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
//Node classes by Viansa S.
import java.util.Iterator;
//represents a Node (with a board and heuristic)
public class Node implements Iterable<Node>, Comparable<Node> {
Board board;
Board.Mark mark;
int heuristic;
public Node() {
this.board = new Board();
this.mark = Board.Mark.X;
heuristic = heuristic();
}
public Node(Board board, Board.Mark mark) {
this.board = board;
this.mark = mark;
}
//returns a linear approximation of the utility of the board
public int heuristic() {
Board.Mark other = mark.other();
int count = 0;
for (Line l : Line.lines()) {
if (board.occupied(l.positions(), other) == 0) {
count += board.occupied(l.positions(), mark);
}
}
return count;
}
public int heuristicDebug() {
Board.Mark other = mark.other();
System.out.print("Mark: " + mark + "\t" + "Other: " + other);
int count = 0;
for (Line l : Line.lines()) {
if (board.occupied(l.positions(), other) == 0) {
count += board.occupied(l.positions(), mark);
}
}
return count;
}
@Override
public Iterator<Node> iterator() {
return new NodeIterator();
}
//Iterator iterates over node's next possible states
public class NodeIterator implements Iterator<Node> {
long emptyPositions;
int position;
public NodeIterator() {
emptyPositions = ~(board.x | board.o);
position = 0;
}
@Override
public boolean hasNext() {
//return true if there's empty spaces that haven't been filled
return emptyPositions != 0;
}
@Override
public Node next() {
//return next possible node
while (!Positions.contains(emptyPositions, position)) {
position++;
}
emptyPositions = Positions.remove(emptyPositions, position);
Board b = new Board(board);
b.set(position, mark);
Node node = new Node(b, mark.other());
position++;
return node;
}
}
public int compareTo(Node other) {
return this.heuristic - other.heuristic;
}
public boolean equals(Node other) {
return this.board.equals(other.board);
}
@Override
public boolean equals(Object other) {
if (other != null && other instanceof Node) {
return equals((Node)other);
}
return false;
}
}