# Program to implement Genetic Algorithm
import random
# Function to optimize
def fitness(x):
return x * x
# Convert binary string to integer
def decode(chromosome):
return int(chromosome, 2)
# Create initial population
def create_population(size, length):
return [''.join([Link]('01') for _ in range(length)) for _ in range(size)]
# Selection: pick best two parents
def selection(population):
[Link](key=lambda c: fitness(decode(c)), reverse=True)
return population[:2]
# Crossover: single point
def crossover(parent1, parent2):
point = [Link](1, len(parent1) - 1)
return parent1[:point] + parent2[point:], parent2[:point] + parent1[point:]
# Mutation: flip a random bit
def mutate(chromosome, rate=0.1):
chromosome = list(chromosome)
for i in range(len(chromosome)):
if [Link]() < rate:
chromosome[i] = '1' if chromosome[i] == '0' else '0'
return ''.join(chromosome)
# Main Genetic Algorithm
def genetic_algorithm():
population_size = 6
chromosome_length = 5
generations = 6
population = create_population(population_size, chromosome_length)
print("Initial Population:", population)
for gen in range(generations):
parents = selection(population)
offspring = []
# Generate offspring using crossover and mutation
for _ in range(population_size // 2):
child1, child2 = crossover(parents[0], parents[1])
[Link](mutate(child1))
[Link](mutate(child2))
population = parents + offspring
population×sort(key=lambda c: fitness(decode(c)), reverse=True)
best = population[0]
print(f"Generation {gen+1}: Best = {best}, f(x) = {fitness(decode(best))}")
print("\nOptimal Solution:")
print("Binary:", best, "→ x =", decode(best), "→ f(x) =", fitness(decode(best)))
# Run program
genetic_algorithm()