piyush0 / EightQueens

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Build Status

Eight Queens

πŸ‘‘ Solution of the famous Eight Queen Problem using bitsets with a touch of Postgres and SQLAlchemy.

Prerequisites

  • Docker
  • Docker Compose

Running the code

For running the source code, use the docker image.

Note

When running the code for the first time, it will also build the underlying docker image

$ docker-compose run app

Sample

Example 1
$ docker-compose run app
1. Run n-queens for a given value of n
2. Store the solutions upto a given value in a database
3. View the database table
4. Clear the database table
5. Run tests
0. Quit

> 1
Enter the value of n
> 8
92
Example 2
$ docker-compose run app
1. Run n-queens for a given value of n
2. Store the solutions upto a given value in a database
3. View the database table
4. Clear the database table
5. Run tests
0. Quit

> 2
Enter the value of n
> 10
Successfully inserted the values
> 3
[(1, 1), (2, 0), (3, 0), (4, 2), (5, 10), (6, 4), (7, 40), (8, 92), (9, 352), (10, 724)]

Project Structure


β”œβ”€β”€ db
β”‚   β”œβ”€β”€ create_answer_table.py       # Initialises the table and DB connections     
β”‚   β”œβ”€β”€ main.py                      # Contains main logic for the DB
β”‚   └── secrets.py                   # Contains secrets. Should be encrypted or not put in Version Control
β”œβ”€β”€ tests                              
β”‚   └── core_test.py                 # Contains unit test cases for core logic
β”œβ”€β”€ helpers                               
β”‚   └── bit_operations.py            # Helper class to deal with bit operations    
β”œβ”€β”€ core.py                          # Contains the logic to solve the problem 
β”œβ”€β”€ main.py                          # Startup script
β”œβ”€β”€ docker-compose.yml               # File to compose app and DB
β”œβ”€β”€ Dockerfile                       # Dockerfile to build app
β”œβ”€β”€ README
β”œβ”€β”€ requirments.txt                  # Specify requirements for the project
└── .gitignore                       # Files to ignore for Version Control

Algorithm

The core algorithm follows the use of bitsets. While checking if it is safe to put the queen at a particular spot, we check whether there is queen in the same column, diagonal 1 or diagonal 2. To check this in O(1) time complexity, we use a number (representing a bitset).

If it was safe to place the queen, we set the appropriate bits in column, diagonal 1, diagonal 2, marking them as occupied and then we go to the next row. If we were able to reach the end of the board, we found 1 solution otherwise we backtrack and unplace the queen means setting off those bits.

Built With

About


Languages

Language:Python 96.5%Language:Dockerfile 3.5%