-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEightPlayer.java
More file actions
422 lines (326 loc) · 14.2 KB
/
Copy pathEightPlayer.java
File metadata and controls
422 lines (326 loc) · 14.2 KB
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Scanner;
/*
* Solves the 8-Puzzle Game (can be generalized to n-Puzzle)
*/
class NodeComparator implements Comparator<Node> {
@Override
public int compare(Node firstNode, Node secondNode) {
// Compare the heuristic values of the two nodes.
if ((firstNode.getgvalue() + firstNode.gethvalue()) < (secondNode.getgvalue() + secondNode.gethvalue())) {
return -1;
} else if ((firstNode.getgvalue() + firstNode.gethvalue()) == (secondNode.getgvalue() + secondNode.gethvalue())) {
return 0;
} else if ((firstNode.getgvalue() + firstNode.gethvalue()) > (secondNode.getgvalue() + secondNode.gethvalue())){
return 1;
}
return 0;
}
};
public class EightPlayer {
static Scanner scan = new Scanner(System.in);
static int size=3; //size=3 for 8-Puzzle.
static int numnodes; //number of nodes generated
static int nummoves; //number of moves required to reach goal
public static void main(String[] args)
{
int numsolutions = 0;
int boardchoice = getBoardChoice();
int algchoice = getAlgChoice();
//determine numiterations based on user's choices
int numiterations = 0;
if(boardchoice==0) {
numiterations = 1;
} else {
switch (algchoice){
case 0:
numiterations = 100;//BFS
break;
case 1:
numiterations = 1000;//A* with Manhattan Distance heuristic
break;
case 2:
numiterations = 1000;//A* with your new heuristic
break;
}
}
Node initNode;
for(int i=0; i<numiterations; i++){
if(boardchoice==0)
initNode = getUserBoard();
else
initNode = generateInitialState();//create the random board for a new puzzle
boolean result=false; //whether the algorithm returns a solution
switch (algchoice){
case 0:
result = runBFS(initNode); //BFS
break;
case 1:
result = runAStar(initNode, 0); //A* with Manhattan Distance heuristic
break;
case 2:
result = runAStar(initNode, 1); //A* with your new heuristic
break;
}
//if the search returns a solution
if(result){
numsolutions++;
System.out.println("Number of nodes generated to solve: " + numnodes);
System.out.println("Number of moves to solve: " + nummoves);
System.out.println("Number of solutions so far: " + numsolutions);
System.out.println("_______");
}
else
System.out.print(".");
}//for
System.out.println();
System.out.println("Number of iterations: " +numiterations);
if(numsolutions > 0){
System.out.println("Average number of moves for "+numsolutions+" solutions: "+nummoves/numsolutions);
System.out.println("Average number of nodes generated for "+numsolutions+" solutions: "+numnodes/numsolutions);
}
else
System.out.println("No solutions in "+numiterations+" iterations.");
}
public static int getBoardChoice()
{
System.out.println("single(0) or multiple boards(1)");
int choice = Integer.parseInt(scan.nextLine());
return choice;
}
public static int getAlgChoice()
{
System.out.println("BFS(0) or A* Manhattan Distance(1) or A* Corner Priority(2)");
int choice = Integer.parseInt(scan.nextLine());
return choice;
}
public static Node getUserBoard()
{
System.out.println("Enter board: ex. 012345678");
String stbd = scan.nextLine();
int[][] board = new int[size][size];
int k=0;
for(int i=0; i<board.length; i++){
for(int j=0; j<board[0].length; j++){
//System.out.println(stbd.charAt(k));
board[i][j]= Integer.parseInt(stbd.substring(k, k+1));
k++;
}
}
// for(int i=0; i<board.length; i++){
// for(int j=0; j<board[0].length; j++){
// System.out.println(board[i][j]);
// }
// System.out.println();
// }
Node newNode = new Node(null,0, board);
return newNode;
}
/**
* Generates a new Node with the initial board
*/
public static Node generateInitialState()
{
int[][] board = getNewBoard();
Node newNode = new Node(null,0, board);
return newNode;
}
/**
* Creates a randomly filled board with numbers from 0 to 8.
* The '0' represents the empty tile.
*/
public static int[][] getNewBoard()
{
int[][] brd = new int[size][size];
Random gen = new Random();
int[] generated = new int[size*size];
for(int i=0; i<generated.length; i++)
generated[i] = -1;
int count = 0;
for(int i=0; i<size; i++)
{
for(int j=0; j<size; j++)
{
int num = gen.nextInt(size*size);
while(contains(generated, num)){
num = gen.nextInt(size*size);
}
generated[count] = num;
count++;
brd[i][j] = num;
}
}
//Case 1: 12 moves
brd[0][0] = 1;
brd[0][1] = 3;
brd[0][2] = 8;
brd[1][0] = 7;
brd[1][1] = 4;
brd[1][2] = 2;
brd[2][0] = 0;
brd[2][1] = 6;
brd[2][2] = 5;
return brd;
}
/**
* Helper method for getNewBoard()
*/
public static boolean contains(int[] array, int x)
{
int i=0;
while(i < array.length){
if(array[i]==x)
return true;
i++;
}
return false;
}
/**
* TO DO:
* Prints out all the steps of the puzzle solution and sets the number of moves used to solve this board.
*/
public static void printSolution(Node node) {
/*TO DO*/
//DOUBLE CHECK THIS
//while the goal of the board order is false (so order is not reached)
ArrayList<Node> listofSolutionPath = new ArrayList<Node>();
//while there is a node, we add the node to the solution past array list.
//the node is now the parent
while(node != null){
listofSolutionPath.add(node);
node = node.getparent();
}
//gets the node in the solution path and sets it as the current node
for (int i = listofSolutionPath.size() - 2; i >= 0; i--){
Node cur_node = listofSolutionPath.get(i);
System.out.println("Step " + (listofSolutionPath.size() - (i+1)) + ": ");
cur_node.print();
nummoves++;
}
}
/**
* TO DO:
* Runs Breadth First Search to find the goal state.
* Return true if a solution is found; otherwise returns false.
*/
public static boolean runBFS(Node initNode)
{
Queue<Node> Frontier = new LinkedList<Node>();
ArrayList<Node> Explored = new ArrayList<Node>();
Frontier.add(initNode);
numnodes++;
int maxDepth = 13;
Node cur_state = null;
/*TO DO*/
while(!Frontier.isEmpty()){
//remove first node from the frontier adn sets it as the current state
cur_state = Frontier.remove();
//add the current state to explored
Explored.add(cur_state);
if(cur_state.getdepth() < maxDepth){
if (cur_state.isGoal()){ //If the current node we're looking at is the goal, then solution is found
System.out.println("Solution Found!");
printSolution(cur_state);
return true;
} else {
ArrayList<int[][]> neighbor_list = cur_state.expand(); //this is the successor boards that are taken from the cur_state
ArrayList<Node> listOfSuccessors = new ArrayList<Node>(); // Changed the type to Node (this is the list of successors to check)
//For loop for creating a new node for every successor and putting them on the successors list
for (int i = 0; i < neighbor_list.size(); i++) {
Node neigh_node = new Node (null,0,neighbor_list.get(i));
listOfSuccessors.add(neigh_node);
}
//traverses through the successors list
for (int i = 0; i < listOfSuccessors.size(); i++) {
Node neighbor = listOfSuccessors.get(i);
neighbor.setparent(cur_state);
neighbor.setdepth(cur_state.getdepth() + 1); //increments the depth of node by 1
if(!Explored.contains(neighbor) && !Frontier.contains(neighbor)){
Frontier.add(neighbor);
numnodes++;
}
}
}
}
}
System.out.println("No solution found");
return false;
}//BFS
/***************************A* Code Starts Here ***************************/
/**
* TO DO:
* Runs A* Search to find the goal state.
* Return true if a solution is found; otherwise returns false.
* heuristic = 0 for Manhattan Distance, heuristic = 1 for your new heuristic
*/
public static boolean runAStar(Node initNode, int heuristic)
{
PriorityQueue<Node> Frontier = new PriorityQueue<Node>(new NodeComparator());
ArrayList<Node> Explored = new ArrayList<Node>();
initNode.setgvalue(0);
if(heuristic == 0){
initNode.sethvalue(initNode.evaluateHeuristic()); //Manhattan Distance heuristic
} else if (heuristic == 1){
initNode.sethvalue(initNode.evaluateHeuristic() + initNode.cornerHeuristic()); //Corner Priority heuristic
}
Frontier.add(initNode);
numnodes++;
int maxDepth = 13;
//while the current state is not the goal and its depth is less than the max depth of 13 and the frontier is not empty
while (!Frontier.isEmpty()){
Node X = Frontier.remove();
Explored.add(X);
//if the first node is the goal, that is the solution
if(X.isGoal()){
System.out.println("Solution Found!");
printSolution(X);
return true;
} else {
if(X.getgvalue() + 1 >= maxDepth){ //Checks to see if the check is reaching the max depth; return false if already over max depth
return false;
} else {
ArrayList<int[][]> neighbor_list = X.expand();
for(int i = 0; i < neighbor_list.size(); i++){
Node child = new Node(X, X.getgvalue() + 1, 0, neighbor_list.get(i)); //Create a new node for every board that are expanded
if(heuristic == 0){//if heuristic is A*Manhattan Distance
child.sethvalue(child.evaluateHeuristic()); //Set h value of the successors using the evaluateHeuristic method
} else if (heuristic == 1){//if heuristic is A*CornerPriority+ManhattanDistance
child.sethvalue(child.evaluateHeuristic() + child.cornerHeuristic()); //Set h value of the successors using the evaluateHeuristic method
}
if(!Explored.contains(child)){//if Explored doesn't contain the successor
if (!Frontier.contains(child)){//if Frontier doesn't contain the successor
Frontier.add(child);
numnodes++;
} else if (Frontier.contains(child)) {
// boolean nodeCheck = false;
// Node nodeHolder = null;
for(Node node : Frontier){//For every node (successor boards) in Frontier
if(node.equals(child)){//If the current node we are traversing is equal to the successor and the current node has a lower f of n value than the successor
if(heuristic == 0){
if((child.getgvalue() + child.gethvalue()) < (node.getgvalue() + node.gethvalue())){ //Manhattan distance
Frontier.remove(node);
Frontier.add(child);
}
} else if (heuristic == 1){
if((child.getgvalue() + child.gethvalue() + child.cornerHeuristic()) < (node.getgvalue() + node.gethvalue() + child.cornerHeuristic())){ //Manhattan Distance + cornerHeuristic
Frontier.remove(node);
Frontier.add(child);
}
}
}
}
}
}
}
}
}
}
System.out.println("No solution!");
return false;
}
}