In this article, a genetic algorithm implementation to solve the 8-queen problem and its generalized version the n-queen problem will be described. This solution technique was presented in one of the lectures in the edX course ColumbiaX: CSMM.101x Artificial Intelligence (AI). The following description of the problem, the genetic algorithm and how it can be applied to solve the problem are taken from the course slides.
Each element in the string is also subject to some mutation with a small probability.
In the 8-queen problem, an individual can be represented by a string digits 1 to 8, that represents the position of the 8 queens in the 8 columns.
Possible fitness function is the number of non-attacking pairs of queens that we are interested to maximize (which has the maximum value \(8 \choose 2\) = 28 for the 8-queen’s problem. In other words we want the number of attacking pairs of queens to be zero in the solution assignment of the queens.
The following figure shows how the crossover and mutation are applied on the candidate genes at different generation.
Data File Format
The following figure shows the pseudocode for the genetic algorithm in its general settings.
Data File Format
The following two figures show the solutions of the 8-queens problem obtained using genetic algorithm. Note that two different solutions are obtained starting with 2 different sets of populations generated using different random seeds.
The following animations show the best-fit chromosome obtained at each generation of the algorithm, starting with different mutation rates. Here the min.cost
variable denote the number of attacking pairs left at any generation. As soon as a solution with 0 cost is obtained, it’s reported and the algorithm execution is stopped.
Also, note that with all other parameters are kept identical, the higher the mutation rate, the longer time the algorithm takes to converge in general.
Convergence of the genetic algorithm With mutation rate 0.3
The algorithm is then generalized to solve the n-queens problem and the following animations show the solutions obtained with two different rates of mutation, for \(n=20\).