0% found this document useful (0 votes)
10 views7 pages

Experiment 6 - N Queen Problem With GA

The document is a lab manual for an MCA course at SVKM's NMIMS, focusing on implementing the N-Queens problem using Genetic Algorithms (GA). It outlines the experiment's aim, prerequisites, expected outcomes, and includes a sample code for the GA implementation. Additionally, it discusses observations, conclusions, and potential applications of GA in various fields, highlighting its advantages and limitations.

Uploaded by

Tarun Purohit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views7 pages

Experiment 6 - N Queen Problem With GA

The document is a lab manual for an MCA course at SVKM's NMIMS, focusing on implementing the N-Queens problem using Genetic Algorithms (GA). It outlines the experiment's aim, prerequisites, expected outcomes, and includes a sample code for the GA implementation. Additionally, it discusses observations, conclusions, and potential applications of GA in various fields, highlighting its advantages and limitations.

Uploaded by

Tarun Purohit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

SVKM’s NMIMS

MPSTME, Mumbai Campus


Computer Engineering Department
Program: MCA, Semester - II
Subject: Artificial Intelligence

LAB Manual

PART A
(PART A: TO BE REFERRED BY STUDENTS)

Experiment No. 6

A.1 AIM: - Write a program to implement n queen problem using Genetic Algorithm (GA)

A.2 Prerequisite
● Different programming language structure overview

A.3 Outcome
● After successful completion of this experiment students will be able to use GA

A.4 Theory:
PART B
(PART B : TO BE COMPLETED BY STUDENTS)

(Students must submit the soft copy as per following segments within two hours of the practical. The soft copy must

be uploaded on the MS Teams)

Roll No. A057 Student Name : Tarun Purohit


Program : MCA Semester : 2

Batch : 3

Date of Experiment : 15/02/2025 Date of Submission : 16/02/2025

B.1 Answers of Task to be written by student:


(Paste your answers completed during the 2 hours of practical in the lab here)

Instruction for Students:

1. Clearly understand the functioning of algorithm.

2. Choose suitable programming language.

3. Write the program to get the goal (solution)

4. Conclude the learning done through the tasks that are implemented.

Tasks to be implemented:

Implement / simulate the behavior of the following informed searching method.

1. Genetic Algorithm
Code:

import random

class NQueensGA:

def __init__(self, n, population_size=100, mutation_rate=0.01):


self.n = n
self.population_size = population_size

self.mutation_rate = mutation_rate

def generate_board(self):

return [random.randint(0, self.n - 1) for _ in range(self.n)]

def fitness(self, board):


collisions = 0
for i in range(len(board)):

for j in range(i + 1, len(board)):


if board[i] == board[j] or abs(i - j) == abs(board[i] - board[j]):

collisions += 1
return collisions

def crossover(self, parent1, parent2):

crossover_point = random.randint(0, self.n - 1)

child = parent1[:crossover_point] + parent2[crossover_point:]


return child

def mutate(self, board):

for i in range(len(board)):
if random.random() < self.mutation_rate:
board[i] = random.randint(0, self.n - 1)
return board

def select_parents(self, population, fitness_scores):


total_fitness = sum(fitness_scores)
probabilities = [score / total_fitness for score in fitness_scores]
parent1 = random.choices(population, probabilities)[0]

parent2 = random.choices(population, probabilities)[0]


return parent1, parent2

def evolve(self, generations):

population = [self.generate_board() for _ in range(self.population_size)]


for generation in range(generations):

fitness_scores = [self.fitness(board) for board in population]


min_fitness = min(fitness_scores)
min_index = fitness_scores.index(min_fitness)
if min_fitness == 0:
print("Solution found:", population[min_index])

return population[min_index]

parents = []
for _ in range(self.population_size // 2):
parent1, parent2 = self.select_parents(population, fitness_scores)
parents.append((parent1, parent2))

population = []

for parent1, parent2 in parents:


child = self.crossover(parent1, parent2)
child = self.mutate(child)
population.append(child)

print("No solution found")

return None

if __name__ == "__main__":

n = 4 # Number of queens
ga = NQueensGA(n)
ga.evolve(generations=1000)

Output:

B.2 Observations and learning:


(Students are expected to comment on the output obtained with clear observations and learning for each task/ sub part assigned)

During the implementation of the N-Queens problem using Genetic Algorithm (GA), it was observed that the algorithm successfully evolved towards an

optimal solution through iterative selection, crossover, and mutation. The population of candidate solutions improved over generations, with the best

individuals showing fewer conflicts. Tournament selection helped in choosing better parents, while order crossover preserved the validity of queen positions.

Swap mutation maintained diversity and avoided premature convergence. A key learning was that GA does not guarantee an immediate solution but offers an

efficient way to approximate solutions in complex search spaces. Additionally, fine-tuning parameters like mutation rate and population size significantly

influenced convergence speed and accuracy.

B.3 Conclusion:
(Students must write the conclusion as per the attainment of individual outcome listed above and learning/observation noted in section B.3)

After experimenting with the Genetic Algorithm implementation for the n-Queens problem in Python, I learned how to utilize GA to efficiently solve complex

combinatorial optimization problems like placing queens on a chessboard without threatening each other.

B.4 Question of Curiosity


(To be answered by student based on the practical performed and learning/observations)
1 What are the main differences between other searching technique and GA?

Genetic Algorithm (GA) differs from traditional search techniques as it follows an evolutionary approach inspired by natural selection, whereas
conventional methods like A* or Dijkstra’s algorithm rely on fixed heuristics and deterministic rules. Unlike structured searches, GA explores large
and complex spaces by maintaining a population of candidate solutions, evolving towards better results over generations. It is highly effective for
optimization problems but does not guarantee an exact solution, making it different from exhaustive or heuristic-based searches. However, GA has
some limitations, including computational expense, sensitivity to parameters like mutation rate and population size, and the risk of premature con-
vergence where it gets stuck in local optima. Additionally, it may not be the best choice for simple problems where deterministic algorithms can
provide exact solutions more efficiently.

Despite these limitations, GA is widely used in various real-world applications. In the Traveling Salesman Problem (TSP), GA helps find the
shortest route between cities, making it useful in logistics and supply chain management. It is also applied in machine learning for hyperparameter
tuning, optimizing models without manual intervention. In scheduling problems, such as job-shop scheduling or exam timetabling, GA ensures
efficient resource allocation while minimizing conflicts. Robotics and path planning benefit from GA by optimizing movement strategies for
autonomous vehicles and robotic arms. Moreover, GA is used in game AI to develop intelligent strategies for board games and real-time strategy
simulations. These diverse applications highlight GA’s effectiveness in solving complex optimization problems where traditional methods struggle.

2 What are the limitations of GA?

 No Guarantee of Optimality: GA provides approximate solutions and may not always find the absolute best solution.
 Computationally Expensive: Requires a large number of iterations and a high population size for good results.
 Parameter Sensitivity: The performance heavily depends on parameters like mutation rate, crossover method, and population size.
 Premature Convergence: May get stuck in local optima instead of exploring better global solutions.
 Not Suitable for Simple Problems: For straightforward tasks, traditional algorithms are more efficient.

3 Discuss other suitable problem statement (application) that can be solved by GA.

(Detail Discussion)

1. Traveling Salesman Problem (TSP)

 GA is used to find the shortest possible route between multiple cities while ensuring each city is visited exactly once.
 Helps in logistics, route optimization, and supply chain management.

2. Machine Learning Hyperparameter Tuning

 GA optimizes parameters like learning rate, number of neurons, and activation functions in deep learning models.
 Improves the accuracy and efficiency of AI models without manual tuning.

3. Scheduling Problems

 Used in job-shop scheduling (allocating machines to tasks) and exam scheduling (minimizing conflicts in exam timetables).
 Ensures optimal use of resources with minimal clashes.
4. Robotics and Path Planning

 Helps robots navigate complex environments by evolving better movement strategies.


 Used in autonomous vehicles and robotic arm path optimization.

5. Game AI and Strategy Optimization

 GA is applied in game AI to evolve intelligent strategies for games like Chess, Tic-Tac-Toe, and real-time strategy (RTS) games.

You might also like