Source Of Summary:

Genetic Algorithm.pdf

1. 🚀 Problem Setup

1.1 🎯 Goal


2. 📚 Genetic Algorithm Parameters

# Maximum capacity of the knapsack (weight limit)
max_weight = 10

# Number of candidate solutions (chromosomes) per generation
population_size = 10

# Probability (0–1) that any gene will mutate (flip bit)
mutation_probability = 0.2

# How many generations to evolve the population
generations = 10

print("\\nGenetic algorithm parameters:")
print("Max weight:", max_weight)
print("Population size:", population_size)
print("Mutation probability:", mutation_probability)
print("Generations:", generations, "\\n")

3. 🧬 Chromosome Representation

3.1 Creating Individuals


4. 🔍 Fitness Function

def fitness(individual):
    """
    Evaluate how good a chromosome is:
    1. Compute total weight = sum(weight_i * gene_i)
    2. Compute total value  = sum(value_i * gene_i)
    3. If weight > max_weight, return 0 (invalid; penalize)
    4. Else return total value as fitness score.
    """
    total_weight = 0
    total_value = 0

    # Sum over all genes
    for i, gene in enumerate(individual):
        if gene == 1:
            # If gene is 1, include this item's weight and value
            total_weight += items[i][0]
            total_value += items[i][1]

    # Penalize overweight solutions
    if total_weight > max_weight:
        return 0

    # Valid solution: return its total value
    return total_value

5. 🏆 Parent Selection