-
Notifications
You must be signed in to change notification settings - Fork 795
/
NQueensDemo.java
203 lines (166 loc) · 8.97 KB
/
NQueensDemo.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
package aima.gui.demo.search;
import aima.core.environment.nqueens.NQueensBoard;
import aima.core.environment.nqueens.NQueensBoard.Config;
import aima.core.environment.nqueens.NQueensFunctions;
import aima.core.environment.nqueens.NQueensGenAlgoUtil;
import aima.core.environment.nqueens.QueenAction;
import aima.core.search.framework.SearchForActions;
import aima.core.search.framework.problem.Problem;
import aima.core.search.framework.qsearch.GraphSearch;
import aima.core.search.framework.qsearch.GraphSearch4e;
import aima.core.search.framework.qsearch.TreeSearch;
import aima.core.search.informed.AStarSearch;
import aima.core.search.local.*;
import aima.core.search.uninformed.BreadthFirstSearch;
import aima.core.search.uninformed.DepthFirstSearch;
import aima.core.search.uninformed.DepthLimitedSearch;
import aima.core.search.uninformed.IterativeDeepeningSearch;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Predicate;
/**
* Demonsrates how different search algorithms perform on the NQueens problem.
* @author Ruediger Lunde
* @author Ravi Mohan
*/
public class NQueensDemo {
private static final int boardSize = 8;
public static void main(String[] args) {
startNQueensDemo();
}
private static void startNQueensDemo() {
solveNQueensWithDepthFirstSearch();
solveNQueensWithBreadthFirstSearch();
solveNQueensWithAStarSearch();
solveNQueensWithAStarSearch4e();
solveNQueensWithRecursiveDLS();
solveNQueensWithIterativeDeepeningSearch();
solveNQueensWithSimulatedAnnealingSearch();
solveNQueensWithHillClimbingSearch();
solveNQueensWithGeneticAlgorithmSearch();
solveNQueensWithRandomWalk();
}
private static void solveNQueensWithDepthFirstSearch() {
System.out.println("\n--- NQueensDemo DFS ---");
Problem<NQueensBoard, QueenAction> problem = NQueensFunctions.createIncrementalFormulationProblem(boardSize);
SearchForActions<NQueensBoard, QueenAction> search = new DepthFirstSearch<>(new TreeSearch<>());
Optional<List<QueenAction>> actions = search.findActions(problem);
actions.ifPresent(qActions -> qActions.forEach(System.out::println));
System.out.println(search.getMetrics());
}
private static void solveNQueensWithBreadthFirstSearch() {
System.out.println("\n--- NQueensDemo BFS ---");
Problem<NQueensBoard, QueenAction> problem = NQueensFunctions.createIncrementalFormulationProblem(boardSize);
SearchForActions<NQueensBoard, QueenAction> search = new BreadthFirstSearch<>(new GraphSearch<>());
Optional<List<QueenAction>> actions = search.findActions(problem);
actions.ifPresent(qActions -> qActions.forEach(System.out::println));
System.out.println(search.getMetrics());
}
private static void solveNQueensWithAStarSearch() {
System.out.println("\n--- NQueensDemo A* (complete state formulation, graph search 3e) ---");
Problem<NQueensBoard, QueenAction> problem = NQueensFunctions.createCompleteStateFormulationProblem
(boardSize, Config.QUEENS_IN_FIRST_ROW);
SearchForActions<NQueensBoard, QueenAction> search = new AStarSearch<>
(new GraphSearch<>(), NQueensFunctions::getNumberOfAttackingPairs);
Optional<List<QueenAction>> actions = search.findActions(problem);
actions.ifPresent(qActions -> qActions.forEach(System.out::println));
System.out.println(search.getMetrics());
}
private static void solveNQueensWithAStarSearch4e() {
System.out.println("\n--- NQueensDemo A* (complete state formulation, graph search 4e) ---");
Problem<NQueensBoard, QueenAction> problem = NQueensFunctions.createCompleteStateFormulationProblem
(boardSize, Config.QUEENS_IN_FIRST_ROW);
SearchForActions<NQueensBoard, QueenAction> search = new AStarSearch<>
(new GraphSearch4e<>(), NQueensFunctions::getNumberOfAttackingPairs);
Optional<List<QueenAction>> actions = search.findActions(problem);
actions.ifPresent(qActions -> qActions.forEach(System.out::println));
System.out.println(search.getMetrics());
}
private static void solveNQueensWithRecursiveDLS() {
System.out.println("\n--- NQueensDemo recursive DLS ---");
Problem<NQueensBoard, QueenAction> problem = NQueensFunctions.createIncrementalFormulationProblem(boardSize);
SearchForActions<NQueensBoard, QueenAction> search = new DepthLimitedSearch<>(boardSize);
Optional<List<QueenAction>> actions = search.findActions(problem);
actions.ifPresent(qActions -> qActions.forEach(System.out::println));
System.out.println(search.getMetrics());
}
private static void solveNQueensWithIterativeDeepeningSearch() {
System.out.println("\n--- NQueensDemo Iterative DS ---");
Problem<NQueensBoard, QueenAction> problem = NQueensFunctions.createIncrementalFormulationProblem(boardSize);
SearchForActions<NQueensBoard, QueenAction> search = new IterativeDeepeningSearch<>();
Optional<List<QueenAction>> actions = search.findActions(problem);
actions.ifPresent(qActions -> qActions.forEach(System.out::println));
System.out.println(search.getMetrics());
}
private static void solveNQueensWithSimulatedAnnealingSearch() {
System.out.println("\n--- NQueensDemo Simulated Annealing ---");
Problem<NQueensBoard, QueenAction> problem =
NQueensFunctions.createCompleteStateFormulationProblem(boardSize, Config.QUEENS_IN_FIRST_ROW);
SimulatedAnnealingSearch<NQueensBoard, QueenAction> search =
new SimulatedAnnealingSearch<>(NQueensFunctions::getNumberOfAttackingPairs,
new Scheduler(20, 0.045, 100));
Optional<List<QueenAction>> actions = search.findActions(problem);
actions.ifPresent(qActions -> qActions.forEach(System.out::println));
System.out.println(search.getMetrics());
System.out.println("Final State:\n" + search.getLastState());
}
private static void solveNQueensWithHillClimbingSearch() {
System.out.println("\n--- NQueensDemo HillClimbing ---");
Problem<NQueensBoard, QueenAction> problem =
NQueensFunctions.createCompleteStateFormulationProblem(boardSize, Config.QUEENS_IN_FIRST_ROW);
HillClimbingSearch<NQueensBoard, QueenAction> search = new HillClimbingSearch<>
(n -> -NQueensFunctions.getNumberOfAttackingPairs(n));
Optional<List<QueenAction>> actions = search.findActions(problem);
actions.ifPresent(qActions -> qActions.forEach(System.out::println));
System.out.println(search.getMetrics());
System.out.println("Final State:\n" + search.getLastState());
}
private static void solveNQueensWithGeneticAlgorithmSearch() {
System.out.println("\n--- NQueensDemo GeneticAlgorithm ---");
FitnessFunction<Integer> fitnessFunction = NQueensGenAlgoUtil.getFitnessFunction();
Predicate<Individual<Integer>> goalTest = NQueensGenAlgoUtil.getGoalTest();
// Generate an initial population
Set<Individual<Integer>> population = new HashSet<>();
for (int i = 0; i < 50; i++)
population.add(NQueensGenAlgoUtil.generateRandomIndividual(boardSize));
GeneticAlgorithm<Integer> ga = new GeneticAlgorithm<>(boardSize,
NQueensGenAlgoUtil.getFiniteAlphabetForBoardOfSize(boardSize), 0.15);
// Run for a set amount of time
Individual<Integer> bestIndividual = ga.geneticAlgorithm(population, fitnessFunction, goalTest, 1000L);
System.out.println("Max time 1 second, Best Individual:\n"
+ NQueensGenAlgoUtil.getBoardForIndividual(bestIndividual));
System.out.println("Board Size = " + boardSize);
System.out.println("# Board Layouts = " + (new BigDecimal(boardSize)).pow(boardSize));
System.out.println("Fitness = " + fitnessFunction.apply(bestIndividual));
System.out.println("Is Goal = " + goalTest.test(bestIndividual));
System.out.println("Population Size = " + ga.getPopulationSize());
System.out.println("Iterations = " + ga.getIterations());
System.out.println("Took = " + ga.getTimeInMilliseconds() + "ms.");
// Run till goal is achieved
bestIndividual = ga.geneticAlgorithm(population, fitnessFunction, goalTest, 0L);
System.out.println("");
System.out.println("Max time unlimited, Best Individual:\n" +
NQueensGenAlgoUtil.getBoardForIndividual(bestIndividual));
System.out.println("Board Size = " + boardSize);
System.out.println("# Board Layouts = " + (new BigDecimal(boardSize)).pow(boardSize));
System.out.println("Fitness = " + fitnessFunction.apply(bestIndividual));
System.out.println("Is Goal = " + goalTest.test(bestIndividual));
System.out.println("Population Size = " + ga.getPopulationSize());
System.out.println("Itertions = " + ga.getIterations());
System.out.println("Took = " + ga.getTimeInMilliseconds() + "ms.");
}
// Here, this trivial algorithm outperforms the genetic search approach as described in the textbook!
private static void solveNQueensWithRandomWalk() {
System.out.println("\n--- NQueensDemo RandomWalk ---");
NQueensBoard board;
int i = 0;
long startTime = System.currentTimeMillis();
do {
i++;
board = new NQueensBoard(boardSize, Config.QUEEN_IN_EVERY_COL);
} while (board.getNumberOfAttackingPairs() > 0);
long stopTime = System.currentTimeMillis();
System.out.println("Solution found after generating " + i + " random configurations ("
+ (stopTime - startTime) + " ms).");
}
}