#背包容量一定 规划放置方案 价值最大
#0-1背包问题
import random
num_items = 6
capacity = 80
weight = [25,15,20,30,20,15]
value = [15,5,10,20,10,10]
pop_size = 50
num_generations = 100
selection_rate = 0.5
mutation_rate = 0.01
#初始化种群函数
def init_population():
population = []
for i in range(pop_size):
chromosome = []
for j in range(num_items):
chromosome.append(random.randint(0,1))#随机初始化染色体填充0,1
population.append(chromosome)#染色体pop_size个形成种群
return population
#计算适应度函数
def fitness(chromosome):
total_weight= 0#初始化
total_value = 0
for i in range(num_items):
if chromosome[i] == 1:
total_weight += weight[i]
total_value += value[i]
if total_weight > capacity:
return 0
else:
return total_value
def selection(population):
population_fitness = []
for chromosome in population:
population_fitness.append(fitness(chromosome))
sorted_population = [x for _, x in sorted(zip(population,population_fitness , population),reverse=True)]#根据降序排列染色体
cutoff = int(selection_rate * len(sorted_population))
return sorted_population[:cutoff]
def crossover(parent1,parent2):
crossover_point = random.randint(0,num_items - 1)
child1 = parent1[:crossover_point] + parent2[crossover_point:]
child2 = parent2[:crossover_point] + parent1[crossover_point:]
return child1, child2
def mutatuion(charomose):
for i in range(num_items):
if random.random() < selection_rate:
j = random.randint(0,num_items - 1)
charomose[i] , charomose[j] = charomose[j], charomose[i]
return charomose
#主函数
def genetic_algorithm():
population = init_population()
for i in range(num_generations):
selected_population = selection(population)
offspring_population = []
for j in range(pop_size - len(selected_population)):
parent1 = random.choice(selected_population)
parent2 = random.choice(selected_population)
child1,child2 = crossover(parent1,parent2)
child1 = mutatuion(child1)
child2 = mutatuion(child2)
offspring_population.append(child1)
offspring_population.append(child2)
population = selected_population + offspring_population
best_chromosome = max(population ,key = fitness)
best_fitness = fitness(best_chromosome)
print("Bset Solution :",best_chromosome)
print("Best Fitness :",best_fitness)
genetic_algorithm()