public static void nQueensGeneticAlgorithmSearch() {
System.out.println("\nNQueensDemo GeneticAlgorithm -->");
try {
int boardSize = 8;
NQueensFitnessFunction fitnessFunction = new NQueensFitnessFunction();
// Generate an initial population
Set<String> population = new HashSet<String>();
for (int i = 0; i < 20; i++) {
population.add(fitnessFunction
.generateRandomIndividual(boardSize));
}
GeneticAlgorithm ga = new GeneticAlgorithm(boardSize,
fitnessFunction.getFiniteAlphabetForBoardOfSize(boardSize),
0.15);
// Run for a set number of iterations
String bestIndividual = ga.geneticAlgorithm(population,
fitnessFunction, 100);
System.out.println("Iterations Best Individual=\n"
+ fitnessFunction.getBoardForIndividual(bestIndividual));
System.out.println("Fitness="
+ fitnessFunction.getValue(bestIndividual));
System.out.println("Is Goal="
+ fitnessFunction.isGoalState(bestIndividual));
System.out.println("Itertions=" + ga.getIterations());
// Run till goal is achieved
bestIndividual = ga.geneticAlgorithm(population, fitnessFunction,
fitnessFunction);
System.out.println("Goal Test Best Individual=\n"
+ fitnessFunction.getBoardForIndividual(bestIndividual));
System.out.println("Fitness="
+ fitnessFunction.getValue(bestIndividual));
System.out.println("Is Goal="
+ fitnessFunction.isGoalState(bestIndividual));
System.out.println("Itertions=" + ga.getIterations());
} catch (Exception e) {
e.printStackTrace();
}