Genetic Algorithm — solving an 8 queens puzzle (2024)

Genetic Algorithm — solving an 8 queens puzzle (3)

Genetic algorithms (GA) try to approach problem solving the way nature and evolution does. The fittest individuals are selected for reproduction in order to produce the offspring of the next generation. In this article we will attempt to solve an 8 queens puzzle using one for educational purposes. An 8 queens is a classic puzzle problem of placing eight chess queens on an 8x8 chessboard so that no two queens threaten each other. Thus no two queens should share the same row, column, or diagonal.

Genetic Algorithm — solving an 8 queens puzzle (4)

The approach we will use when tackling the 8 queens problem Firstly, we ‘ll seek for a list combination that gives zero cost on the cost function, which means that no queen is attacking the other queen.

We assume that each queen belongs in a separate row, otherwise they would already attack each other. For example the chess board on the right would be decoded as [3,1,6,2,5,7,4,0] . Our goal is to find one such permutation.

Analytically the process entails the following steps:

  • Initialization: A population of suitable size of suitable length is created.The population size should not be kept very large as it can cause a GA to slow down, while a smaller population might not be enough for a good mating pool. Therefore, an optimal population size needs to be decided by trial and error.
  • Selection: it involves the selection of a subset of the best results from the current population, that is the 8-queens outcomes which have the minimum cost function. In our case we’ll keep 20% of the population.
  • Crossover: Picking this subset we’ll randomly pick 2 of those words each time and crossover them. Picking a random length from 0,8 that is the length of the Queens states we ll take the first bit of the first word and concatenate it with the second word of the second bit

A visual below shows what happens:

Genetic Algorithm — solving an 8 queens puzzle (5)
  • Mutation: The mutation is manifested with a small random change in the combination of the individuals. This mutation happens once in a small probability. In our case it’s 30% of the time.

The below does nothing more but the above described in one routine:

Lastly an EightQueensState class representation is needed for everything to work:

A double for loop for every chess position like below would visualize our solution:

Genetic Algorithm — solving an 8 queens puzzle (6)

So now our algorithm is working. But let’s turn it up a notch, taking a few extra steps and extend our application:

  • First let’s make queens accept any number of queens.
  • Since we have a permutation, it makes sense to take advantage of that and not treat it like an integer representation. Changing to a permutation instead of an integer should bring a bettwer outcome faster.
  • Lastly implement Davis’ Order Crossover and change mutation function.

We tried to use OX1 to gain faster results. What we did in our new crossover function involves the following steps.

  1. Create two random crossover points in the first parent copy the segment between them from the first parent to the offspring.
  2. Starting from the second crossover point in the second parent, copy the remaining unused numbers from the second parent to the first child wrapping around the list.
  3. Do the same for the second child with the first parent now being the second and vise versa.
  4. Since keeping them same mutation function or erasing it either breaks the application cause we would have more than one occurrences of the same number and this would break OX1 implementation or converges really fast getting stack in trying to find a combination where it doesn’t exist. We implemented a mutation function that every 30% of the time just inputs a random permutation of a new individual.

Example of David’s Crossover [2]

Genetic Algorithm — solving an 8 queens puzzle (7)

Now let’s make a consistent way of judging whether our enhancements indeed increase the efficiency of our algorithm timewise. So, we create a loop for the first 100 seeds and calculate the time it took the algorithm to find an optimal solution.

Adding a plot and statitics for the mean, average, variance, max, min will give us a feel for how good we did.

This plots shows our initial times:

Genetic Algorithm — solving an 8 queens puzzle (8)

The enhanced version clearly shows a significant increase in the efficiency of the algorithm.

Genetic Algorithm — solving an 8 queens puzzle (9)

The complete project is on GitHub https://github.com/nikkaramessinis/Genetic-Algorithm

If you liked the content please consider following Nick Karamessinis or https://www.buymeacoffee.com/nikaramesinis. For any corrections or additions you are more than welcome to comment for more discussion.

References

[1] Artificial Intelligence A Modern Approach Third Edition. (n.d.).

[2]Genetic Algorithm: 8 Queens Problem | by Cheng Xi Tsou | Nerd For Tech | Medium. (n.d.). Retrieved January 18, 2022, from

https://medium.com/nerd-for-tech/genetic-algorithm-8-queens-problem-b01730e673fd

[3] Genetic Algorithms — Quick Guide. (n.d.). Retrieved January 18, 2022, from https://www.tutorialspoint.com/genetic_algorithms/genetic_algorithms_quick_guide.htm

Genetic Algorithm — solving an 8 queens puzzle (2024)

FAQs

Is there a solution to the 8 queens problem? ›

"The eight queens puzzle is the problem of placing eight chess queens on an 8×8 chessboard so that no two queens threaten each other; thus, a solution requires that no two queens share the same row, column, or diagonal. There are 92 solutions.

How many possible solutions exist for an 8 queen problem *? ›

The eight queens puzzle has 92 distinct solutions. If solutions that differ only by the symmetry operations of rotation and reflection of the board are counted as one, the puzzle has 12 solutions. These are called fundamental solutions; representatives of each are shown below.

Which algorithm is used to solve the 8 queens problem? ›

Which algorithm is used to solve 8 queens problem? One common algorithm used to solve the 8 Queens Problem is the backtracking algorithm, which tries to place queens on the chessboard column by column, checking if each placement is valid and backtracking if it is not.

What is the 8-queen puzzle in AI? ›

The initial state is given by the empty chess board. Placing a queen on the board represents an action in the search problem. A goal state is a configuration where none of the queens attacks any of the others. Note that every goal state is reached after exactly 8 actions.

How do you solve an queen problem? ›

Solution to the N-Queens Problem

We place one queen in each row/column. If we see that the queen is under attack at its chosen position, we try the next position. If a queen is under attack at all the positions in a row, we backtrack and change the position of the queen placed prior to the current position.

What is the prize for the 8 queens problem? ›

The underlying problem is one of the most major unsolved problems in computer science and mathematics. Known as P versus NP, it is one of the seven Millennium Prize Problems which carry the million dollar reward for their first correct solution.

What is the complexity of the 8 queens problem? ›

A simple brute-force solution would be to generate all possible chess boards with 8 queens. Accordingly, there would be N^2 positions to place the first queen, N^2 – 1 position to place the second queen and so on. The total time complexity, in this case, would be O(N^(2N)), which is too high.

What is the brute-force solution to the 8 queens problem? ›

The simplest solution to the 8-Queens puzzle is to use a brute-force search algorithm, which considers all 648 = 281,474,976,710,656 possible blind placements of eight queens, and then removing all placements that place two queens, either on the same space, or in mutually attacking positions.

How to put 8 queens on a chessboard without threatening each other? ›

Placing queens on a chessboard using the knight's move to separate them can be quite a good strategy for playing eight queens. If you remove the black knights from Figure 1a and replace the four white knights with four queens, then no two queens are threatening each other (Figure 1b).

Which technique is commonly used to solve the n-queens problem? ›

The backtracking algorithm is used to solve the N queen problem, in which the board is recursively filled with queens, one at a time, and backtracked if no valid solution is found. At each step, the algorithm checks to see if the newly placed queen conflicts with any previously placed queens, and if so, it backtracks.

How many fundamental solutions are there for the eight queen puzzle 92 10 11 12? ›

Explanation: For 8*8 chess board with 8 queens there are total of 92 solutions for the puzzle. There are total of 12 fundamental solutions to the eight queen puzzle.

Which is the best algorithm to solve 8 puzzle problem? ›

A* is an informed search algorithm that combines the cost to reach a state (g-value) with a heuristic estimate of the cost to reach the goal (h-value). It is widely used for solving problems like the 8-puzzle, as it finds optimal solutions efficiently. A* relies on an admissible heuristic to guide the search.

What is the 8 queen problem using genetic algo? ›

8 queens is a classic computer science problem. To find possible arrangements of 8 queens on a standard 8 x 8 chessboard such that no queens every end up in an attacking configuration. Now, if one knows the basics of chess, one can say that a queen can travel either horizontally, vertically, or diagonally.

What are the implicit constraints for 8 queens problem? ›

No two queens on the same column

This constraint is implicit in the definition of queens . Since no two elements of queens can have the same index, no two queens can be in the same column.

What is the fitness function in genetic algorithm 8 queens problem? ›

The proposed fitness function is based on the chessboard arrangement, and in particular, it is inversely proportional to the number of clashes amongst attacking positions of queens; thus, a high fitness value implies a low number of clashes. This can be calculated quite easily in the context of 8-queen problem.

What is the N Queens problem genetic algorithm? ›

N-Queens problem refers to the problem in which one has to place N- Queens on an n×n chessboard such that no queen is attacking the other, i.e. no two queens occupy the same row, column or diagonal. Here we use Genetic Algorithm to obtain a new breed by crossing of their predecessor.

Which technique is used to solve N queen problem? ›

The backtracking algorithm is used to solve the N queen problem, in which the board is recursively filled with queens, one at a time, and backtracked if no valid solution is found. At each step, the algorithm checks to see if the newly placed queen conflicts with any previously placed queens, and if so, it backtracks.

Top Articles
Latest Posts
Article information

Author: Dong Thiel

Last Updated:

Views: 6088

Rating: 4.9 / 5 (79 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Dong Thiel

Birthday: 2001-07-14

Address: 2865 Kasha Unions, West Corrinne, AK 05708-1071

Phone: +3512198379449

Job: Design Planner

Hobby: Graffiti, Foreign language learning, Gambling, Metalworking, Rowing, Sculling, Sewing

Introduction: My name is Dong Thiel, I am a brainy, happy, tasty, lively, splendid, talented, cooperative person who loves writing and wants to share my knowledge and understanding with you.