编写一个简单的C语言遗传算法程序
时间: 2023-02-22 20:17:29 浏览: 92
用C语言编写的遗传算法程序
4星 · 用户满意度95%
首先,遗传算法是一种仿照生物遗传进化过程的演算法,用于求解优化问题。
以下是一个简单的C语言遗传算法程序:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define POPULATION_SIZE 100
#define CHROMOSOME_LENGTH 10
#define MAX_GENERATIONS 1000
void initializePopulation(int population[][CHROMOSOME_LENGTH]);
void evaluateFitness(int population[][CHROMOSOME_LENGTH], int fitness[]);
void selectParents(int population[][CHROMOSOME_LENGTH], int fitness[], int parent1[], int parent2[]);
void crossover(int parent1[], int parent2[], int offspring1[], int offspring2[]);
void mutate(int offspring1[]);
void replacePopulation(int population[][CHROMOSOME_LENGTH], int offspring1[], int offspring2[]);
int main() {
int population[POPULATION_SIZE][CHROMOSOME_LENGTH];
int fitness[POPULATION_SIZE];
int parent1[CHROMOSOME_LENGTH];
int parent2[CHROMOSOME_LENGTH];
int offspring1[CHROMOSOME_LENGTH];
int offspring2[CHROMOSOME_LENGTH];
int generation;
srand(time(NULL));
initializePopulation(population);
for (generation = 0; generation < MAX_GENERATIONS; generation++) {
evaluateFitness(population, fitness);
selectParents(population, fitness, parent1, parent2);
crossover(parent1, parent2, offspring1, offspring2);
mutate(offspring1);
mutate(offspring2);
replacePopulation(population, offspring1, offspring2);
}
return 0;
}
void initializePopulation(int population[][CHROMOSOME_LENGTH]) {
int i, j;
for (i = 0; i < POPULATION_SIZE; i++) {
for (j = 0; j < CHROMOSOME_LENGTH; j++) {
population[i][j] = rand() % 2;
}
}
}
void evaluateFitness(int population[][CHROMOSOME_LENGTH], int fitness[]) {
int i, j;
for (i = 0; i < POPULATION_SIZE; i++) {
fitness[i] = 0;
for (j = 0; j < CHROMOSOME_LENGTH; j++) {
fitness[i] += population[i][j];
}
}
}
void selectParents(int population[][CHROMOSOME_LENGTH], int fitness[], int parent1[], int parent2[]) {
int i, j, sum;
int r
阅读全文