{"id":22720856,"url":"https://github.com/open-byte/n-queens-genetic-algorithm","last_synced_at":"2025-10-26T04:36:51.040Z","repository":{"id":193914075,"uuid":"526016826","full_name":"open-byte/n-queens-genetic-algorithm","owner":"open-byte","description":"Genetic Algorithm for Solving NQueens Problem","archived":false,"fork":false,"pushed_at":"2023-09-10T18:01:39.000Z","size":184,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-08-08T05:48:02.707Z","etag":null,"topics":["algorithm","genetic-algorithm","nqueens","nqueens-problem","nqueens-problem-solver","nqueens-solution","python"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/open-byte.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-08-18T01:49:33.000Z","updated_at":"2023-10-16T13:33:50.000Z","dependencies_parsed_at":null,"dependency_job_id":"690eedef-88fb-4211-beb1-44dd11f56ebc","html_url":"https://github.com/open-byte/n-queens-genetic-algorithm","commit_stats":null,"previous_names":["open-byte/n-queens-genetic-algorithm"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/open-byte/n-queens-genetic-algorithm","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/open-byte%2Fn-queens-genetic-algorithm","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/open-byte%2Fn-queens-genetic-algorithm/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/open-byte%2Fn-queens-genetic-algorithm/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/open-byte%2Fn-queens-genetic-algorithm/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/open-byte","download_url":"https://codeload.github.com/open-byte/n-queens-genetic-algorithm/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/open-byte%2Fn-queens-genetic-algorithm/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":270771810,"owners_count":24642371,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-16T02:00:11.002Z","response_time":91,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["algorithm","genetic-algorithm","nqueens","nqueens-problem","nqueens-problem-solver","nqueens-solution","python"],"created_at":"2024-12-10T14:11:58.525Z","updated_at":"2025-10-26T04:36:50.933Z","avatar_url":"https://github.com/open-byte.png","language":"Python","readme":"# Genetic Algorithm for Solving NQueens Problem\n\n## Introduction\n\nThis is a simple implementation of the [Genetic Algorithm](https://en.wikipedia.org/wiki/Genetic_algorithm) for solving the [N-Queens problem](https://en.wikipedia.org/wiki/Eight_queens_puzzle).\n\nThe N-Queens problem is to place N queens on an N×N chessboard so that no two queens attack each other.\n\nThe problem can be stated as follows:\n\n\u003e Given an integer N, place N queens on an N×N chessboard so that no two queens attack each other.\n\n\u003e\u003e Note: This solution is not optimal. It is just a simple implementation.\n\n### Requirements\n- Python 3.8+\n- Colorama (for colored output)\n\n## Installation\n- Create a virtual environment and install dependencies\n\n    ```bash\n    $ python3 -m venv env\n    $ source env/bin/activate\n    $ pip install -r requirements.txt\n    ```\n- Run the program\n\n    ```bash\n    $ python3 n_queen.py\n    ```\n\n- Run the program with the `--help` flag to see the available options\n- Run the program with the arguments:\n    \n    ```bash \n    $ python n_queen.py --n-queen 10 --population 1000 --mutation-probability 40 --generations 1000\n    ## or\n    $ python n_queen.py -n 10 -p 1000 -m 40 -g 1000\n    ```\n## Implementation Details\n\nThe algorithm is implemented in the following steps:\n\n1. Generate a random population of N-queens solutions.\n2. Evaluate the fitness of each solution.\n3. Select the best solutions from the population.\n4. Cross-over the best solutions to generate new solutions.\n4. Repeat the above steps until the termination condition is met.\n\nThe termination condition is when the best solution is found or generation limit is reached.\n\n\n## Implementation\n\n### Generate a random population of N-queens solutions\n```python\ndef _create_generation(self) -\u003e None:\n        \"\"\"\n        Create new generation\n        \"\"\"\n        self.current_generation += 1\n        new_population: List[Gen] = []\n        population = self.population ## copy of population optimization\n        length_population = len(population) - 1 ## we want to position 0 to length - 1\n        \n        for _ in range(length_population):\n            ## Gen selection 1 (tournament selection)\n            gen_1 = population[random.randint(0, length_population)]\n            gen_2 = population[random.randint(0, length_population)]\n            selected_gen_1 = gen_1 if gen_1.fitness \u003c gen_2.fitness else gen_2\n\n            ## Gen selection 2 (tournament selection)\n            gen_1 = population[random.randint(0, length_population)]\n            gen_2 = population[random.randint(0, length_population)]\n            selected_gen_2 = gen_1 if gen_1.fitness \u003c gen_2.fitness else gen_2\n            \n            ## crossover and mutation\n            new_gen = self._crossover(selected_gen_1, selected_gen_2)\n            new_population.append(new_gen)\n        \n        new_population.append(self.best_gen)\n        \n        self.population = new_population\n```\n### Crossover and mutation\n```python\ndef _crossover(self, gen_1: Gen, gen_2: Gen) -\u003e Gen:\n        \"\"\"\n        index = random.randint(0, self.n_queen - 1) =\u003e 3 random crossover \n        gen1: [3,4,2,1,0,5,6,7]\n        gen2: [4,3,2,7,1,3,5,7]\n        new_gen: gen1[0:3] + gen2[3:n_queen - 1] = [3,4,2,7,1,3,5,7]\n\n        ## mutation\n        gen = [3,4,2,7,1,3,6,7]\n        mutated_gen = [3,*1,2,7,1,3,*5,7] ## * is a placeholder for mutation\n        \"\"\"\n        n_queen = self.n_queen\n        index = random.randint(0, n_queen - 1)\n        gen_solution = gen_1.gen[0:index] + gen_2.gen[index:]\n        \n\n        # mutation: value of new_gen\n        mutation_probability = self.mutation_probability\n        for i in range(n_queen):\n            if random.randint(0, 100) \u003c mutation_probability:\n                gen_solution[i] = random.randint(0, n_queen - 1)\n                \n        new_gen = Gen(gen=gen_solution, generation=self.current_generation)\n        \n        return new_gen\n        \n```\n### Evaluate the fitness of each solution\n```python\ndef _calculate_fitness(self) -\u003e int:\n        \"\"\"\n        Calculate fitness of the gen\n        \"\"\"\n        \n        fitness = 0\n        gen = self.gen\n        for q_row, q_column in enumerate(gen):\n            for q_row2, q_column2 in enumerate(gen[q_row + 1:], start=q_row + 1):\n                row_diff = abs(q_row - q_row2)\n                col_diff = abs(q_column - q_column2)\n                if row_diff == col_diff:\n                    # diagonal conflict\n                    fitness += 1\n\n                # same column [1,0, 1] row 0 and row 2 have same column\n                elif q_column == q_column2:\n                    # same row conflict\n                    fitness += 1\n\n                else:\n                    # no conflict\n                    fitness += 2\n\n        return fitness\n```\n\n\n\n### Solve the N-Queens problem\n```python\ndef solve(self, generation_number) -\u003e int:\n    \"\"\"\n    Return number of generations needed to solve the problem\n    if no solution found return -1\n    \"\"\"\n    \n    solved_generation = 0\n    best_fitness = self.best_fitness\n    if self.best_gen.fitness == best_fitness:\n        generation = solved_generation\n    \n    else:\n        for k in range(generation_number):\n            self._create_generation()\n            \n            if self.best_gen.fitness == best_fitness:\n                generation  = solved_generation + k\n            \n        generation = -1\n    \n    return generation\n```\n## Examples:\n\n1 - When the N-Queens **problem is solved**, the following is printed:\n\n```bash\n$ python n_queen.py --n-queen 8 --population 1000 --mutation-probability 35 --generations 5000\n```\n\n![result](./images/solution-found.png)\n\n2 - When the N-Queens problem **is not solved**, the following is printed:\n\n```bash\n$ python n_queen.py --n-queen 8 --population 100 --mutation-probability 35 --generations 500\n```\n![result](./images/solution-not-found.png)\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fopen-byte%2Fn-queens-genetic-algorithm","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fopen-byte%2Fn-queens-genetic-algorithm","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fopen-byte%2Fn-queens-genetic-algorithm/lists"}