编写一个C语言的遗传算法程序
时间: 2023-02-22 21:58:33 浏览: 47
下面是一个简单的C语言遗传算法的例子:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define POPULATION_SIZE 100
#define GENE_LENGTH 10
#define MAX_GENERATIONS 1000
// 随机生成0/1基因
int generate_gene() {
return rand() % 2;
}
// 生成一个随机的初始种群
void generate_population(int population[][GENE_LENGTH]) {
int i, j;
for (i = 0; i < POPULATION_SIZE; i++) {
for (j = 0; j < GENE_LENGTH; j++) {
population[i][j] = generate_gene();
}
}
}
// 计算一个个体的适应度
int calculate_fitness(int individual[]) {
int i, fitness = 0;
for (i = 0; i < GENE_LENGTH; i++) {
fitness += individual[i];
}
return fitness;
}
// 进行一次遗传操作
void perform_genetic_operation(int population[][GENE_LENGTH]) {
int i, j, parent1, parent2, offspring[GENE_LENGTH];
int parent1_fitness, parent2_fitness;
// 选择两个父代个体
parent1 = rand() % POPULATION_SIZE;
do {
parent2 = rand() % POPULATION_SIZE;
} while (parent1 == parent2);
// 计算父代的适应度
parent1_fitness = calculate_fitness(population[parent1]);
parent2_fitness = calculate_fitness(population[parent2]);
// 基于适应度,选择更优的父代作为生成后代的父代
int * better_parent;
if (parent1_fitness > parent2_fitness) {
better_parent = population[parent1];
} else {
better_parent = population[parent2];
}
// 生成后代
for (i = 0; i < GENE_LENGTH; i++) {
offspring[i] = better_parent[i];
}
// 进行突变
int mutation_point = rand() % GENE_LENGTH;
offspring[mutation_point] = (offspring[mutation_point] + 1) % 2;
// 将后代加入种群
int worst_individual = 0;
int worst_fitness = calculate_fitness(population[0]);