-
Notifications
You must be signed in to change notification settings - Fork 1
/
NQueens.java
349 lines (298 loc) · 8.22 KB
/
NQueens.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
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
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
/**
*
* @author Shania Dicen
*
*/
public class NQueens {
public static void main(String[] args) {
NQueens program = new NQueens();
program.run();
}
public void run() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter an integer for N-Queens (N>3): ");
int size = Integer.parseInt(sc.nextLine());
sc.close();
if (size <= 3) {
System.out.println("Board size must be greater than 3.");
} else {
Board startBoard = new Board(size);
System.out.println("=================Board Specification=================\n" + "N-Queens Board Size: "
+ size + "\nEvaluation Function: " + startBoard.getSafeQueenPairs()
+ "\nStart Board Configuration:\n" + startBoard.toString());
System.out.println("--Results for Hill Climbing Algorithm--\n");
hillClimbing(startBoard);
System.out.println("\n\n--Results for Random Restart Algorithm--\n");
randomRestart(startBoard);
}
}
/**
* Implementation of the Hill Climbing Algorithm for N-Queens Problem.
*
* @param board
*/
public void hillClimbing(Board board) {
boolean isLocalMax = false, continueSearch = true;
Board currentBoard = new Board(board.getBoard()); // copy of the board
int iterations = 0;
int globalMax = getGoalValue(currentBoard.getBoard().length);
while (continueSearch) {
if (currentBoard.getSafeQueenPairs() == globalMax) { // check if the board configuration is the goal board
System.out.println("=================Solution Found=================" + "\nNumber of iterations: "
+ iterations + "\nEvaluation Function: " + currentBoard.getSafeQueenPairs()
+ "\nBoard Configuration:\n" + currentBoard.toString());
continueSearch = false;
break;
} else {
for (int i = 0; i < currentBoard.getBoard().length; i++) {
Board bestSuccessor = generateSuccessor(currentBoard, i);
if (bestSuccessor.getSafeQueenPairs() > currentBoard.getSafeQueenPairs()) {
currentBoard = bestSuccessor;
iterations++;
isLocalMax = false;
} else {
isLocalMax = true;
}
}
if (isLocalMax) {
System.out.println(
"=================Local Maximum Encoutered=================" + "\nNumber of iterations: "
+ iterations + "\nEvaluation Function: " + currentBoard.getSafeQueenPairs()
+ "\nLocal Maximum Board Configuration:\n" + currentBoard.toString());
continueSearch = false;
break;
}
}
}
}
/**
* Implementation of the Random Restart Algorithm for N-Queens Problem.
*
* @param board
*/
public void randomRestart(Board board) {
Board currentBoard = new Board(board.getBoard());
int iterations = 0, numRestarts = 0, numLocalMax = 0, totalIterations = 0, average = 0;
int globalMax = getGoalValue(currentBoard.getBoard().length);
boolean isLocalMax = false, continueSearch = true;
while (continueSearch) {
totalIterations += iterations;
if (currentBoard.getSafeQueenPairs() == globalMax) { // check if the board configuration is the goal board
try {
average = totalIterations / numLocalMax;
} catch (Exception e) {
}
System.out.println("=================Solution Found=================" + "\nEvaluation Function: "
+ currentBoard.getSafeQueenPairs() + "\nNumber of Restarts: " + numRestarts
+ "\nAverage length of each 'run': " + average + "\nNumber of Iterations: " + iterations
+ "\nBoard Configuration:\n" + currentBoard.toString());
continueSearch = false;
break;
} else {
for (int x = 0; x < currentBoard.getBoard().length; x++) {
Board bestSuccessor = generateSuccessor(currentBoard, x);
if (bestSuccessor.getSafeQueenPairs() > currentBoard.getSafeQueenPairs()) {
currentBoard = bestSuccessor;
iterations++;
isLocalMax = false;
} else {
isLocalMax = true;
}
}
if (isLocalMax) {
numRestarts++;
numLocalMax++;
currentBoard = new Board(currentBoard.getBoard().length);
}
}
}
}
/**
* Generates the best successor based from the given board configuration. Moves
* the Queen on a specified row to an unoccupied column
*
* @return
*/
public Board generateSuccessor(Board board, int row) {
ArrayList<Board> children = new ArrayList<Board>();
Board bestChild;
for (int col = 0; col < board.getBoard().length; col++) {
if (board.getBoard()[row][col] != 1) { // the element is not a queen
int child[][] = new int[board.getBoard().length][board.getBoard().length];
child[row][col] = 1; // move queen to this column
for (int i = 0; i < child.length; i++) {
if (i != row) {
child[i] = board.getBoard()[i];
}
}
children.add(new Board(child)); // create board object from the generated new board
// add successor to children list
}
}
bestChild = children.get(0);
for (int z = 1; z < children.size(); z++) {
int bestEv = bestChild.getSafeQueenPairs();
int nextEv = children.get(z).getSafeQueenPairs();
if (nextEv > bestEv) {
bestChild = children.get(z);
} else if (nextEv == bestEv) {
Random rand = new Random();
int choose = (int) (rand.nextInt(2));
if (choose == 1) {
bestChild = children.get(z);
}
}
}
return bestChild;
}
/**
* Returns the sum of the integers from 1 up to (N-1) [sum(1,2,3,...,N-1)]
*
* @return
*/
public int getGoalValue(int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += i;
}
return sum;
}
}
class Board {
private int board[][];
private int safeQueenPairs; // number of non-attacking pair of queens
/**
* Generates a board object from a given 2 dimensional board array
*
* @param b
*/
public Board(int[][] b) {
this.board = b;
ev();
}
/**
* Generates a board with random placement of queens on each row given the board
* size.
*
* @param size
*/
public Board(int size) {
board = new int[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
board[i][j] = 0;
}
}
generateRandomQueens(size);
ev();
}
/**
* Generates a random queen on each row of the matrix given the board size.
*
* @param size
*/
public void generateRandomQueens(int size) {
Random rand = new Random();
for (int i = 0; i < size; i++) {
board[i][rand.nextInt(size - 1)] = 1;
}
}
public int ev() {
safeQueenPairs = 0;
ArrayList<Integer> pos = getQueenPositions();
for (int i = 0; i < board.length - 1; i++) {
safeQueenPairs += countSafe(pos, i);
}
return safeQueenPairs;
}
public int countSafe(ArrayList<Integer> pos, int row) {
int i, safePairQ = 0, count = 0;
for (i = row; i < board.length - 1; i++) {
count = 0;
if (pos.get(row) == pos.get(i + 1)) { // check if same column
count++;
}
if ((pos.get(row) + row) == (pos.get(i + 1) + (i + 1))) { // check diagonal
count++;
}
if ((pos.get(row) - row) == (pos.get(i + 1) - (i + 1))) { // check diagonal
count++;
}
if (count <= 0) {
safePairQ++;
}
}
return safePairQ;
}
public ArrayList<Integer> getQueenPositions() {
ArrayList<Integer> pos = new ArrayList<Integer>();
for (int i = 0; i < board.length; i++) {
pos.add(getColumn(i));
}
return pos;
}
/**
* @return the board
*/
public int[][] getBoard() {
return board;
}
/**
* @param board
* the board to set
*/
public void setBoard(int[][] board) {
this.board = board;
}
/**
* @return the safeQueenPairs
*/
public int getSafeQueenPairs() {
return safeQueenPairs;
}
/**
* @param safeQueenPairs
* the safeQueenPairs to set
*/
public void setSafeQueenPairs(int safeQueenPairs) {
this.safeQueenPairs = safeQueenPairs;
}
/**
* Returns the index of a column given a row (index of queen on a given row)
*
* @param row
* @return index
*/
public int getColumn(int row) {
int index = 0;
for (int i = 0; i < board.length; i++) {
if (board[row][i] == 1) {
index = i;
}
}
return index;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
String b = "";
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
if (board[i][j] == 0) {
b += " * ";
} else {
b += " Q ";
}
}
b += "\n";
}
return b;
}
}