Professional Documents
Culture Documents
Total Marks: 50
Obtained Marks:
Evolutionary Computing
Assignment # 1
EC BS(AI)- SZABIST-ISB
Shaheed Zulfikar Ali Bhutto Institute of Science & Technology
Theoretical Part:
Pseudocode for the solution of given problem by explaining each step by
using GA in your own words:
EC BS(AI)- SZABIST-ISB
Shaheed Zulfikar Ali Bhutto Institute of Science & Technology
EC BS(AI)- SZABIST-ISB
Shaheed Zulfikar Ali Bhutto Institute of Science & Technology
Implementation Part:
a) Applying midpoint crossover for the next generation of candidates:
Code:
import random
board_size = 8
num_queens = 8
EC BS(AI)- SZABIST-ISB
Shaheed Zulfikar Ali Bhutto Institute of Science & Technology
def fitness(chromosome):
non_attacking_pairs = 0
for i in range(num_queens):
for j in range(i+1, num_queens):
if chromosome[i] != chromosome[j] and abs(chromosome[i] -
chromosome[j]) != j - i:
non_attacking_pairs += 1
return non_attacking_pairs
def selection(population):
def mutation(chromosome):
EC BS(AI)- SZABIST-ISB
Shaheed Zulfikar Ali Bhutto Institute of Science & Technology
population_size = 100
population = [[random.randint(0, board_size-1) for _ in range(num_queens)] for
_ in range(population_size)]
max_generations = 1000
for generation in range(max_generations):
child1 = mutation(child1)
child2 = mutation(child2)
b) Applying mutation for the next generation of candidates and providing the
diversity in the solution:
EC BS(AI)- SZABIST-ISB
Shaheed Zulfikar Ali Bhutto Institute of Science & Technology
Code:
import random
board_size = 8
num_queens = 8
def fitness(chromosome):
non_attacking_pairs = 0
for i in range(num_queens):
for j in range(i+1, num_queens):
if chromosome[i] != chromosome[j] and abs(chromosome[i] -
chromosome[j]) != j - i:
non_attacking_pairs += 1
return non_attacking_pairs
def selection(population):
def mutation(chromosome):
EC BS(AI)- SZABIST-ISB
Shaheed Zulfikar Ali Bhutto Institute of Science & Technology
population_size = 100
population = [[random.randint(0, board_size-1) for _ in range(num_queens)] for
_ in range(population_size)]
max_generations = 1000
for generation in range(max_generations):
child1 = mutation(child1)
child2 = mutation(child2)
population.append(child1)
population.append(child2)
EC BS(AI)- SZABIST-ISB
Shaheed Zulfikar Ali Bhutto Institute of Science & Technology
population.pop(worst_indices[1])
The End.
EC BS(AI)- SZABIST-ISB