用c++写遗传算法代码
时间: 2023-04-09 16:01:32 浏览: 131
我可以回答这个问题。遗传算法是一种优化算法,可以用于解决许多问题,如函数优化、组合优化等。在C语言中,可以使用结构体来表示个体,使用数组来表示种群,使用随机数生成函数来实现遗传算法的随机性。具体实现可以参考相关的遗传算法教程和代码示例。
相关问题
用c++写出遗传算法代码
以下是一个简单的遗传算法的C++实现代码。该代码实现了遗传算法的基本流程:初始化种群、计算适应度、选择、交叉、变异等操作。这个实现是一个通用的框架,可以用来解决各种优化问题,只需要根据具体问题定义相应的适应度函数即可。
```c++
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <random>
using namespace std;
//定义个体
struct Individual {
vector<int> genes; //基因序列
double fitness; //适应度
};
//初始化种群
vector<Individual> initializePopulation(int populationSize, int geneLength) {
vector<Individual> population(populationSize);
for (int i = 0; i < populationSize; ++i) {
for (int j = 0; j < geneLength; ++j) {
population[i].genes.push_back(rand() % 2);
}
}
return population;
}
//计算适应度
void calculateFitness(vector<Individual>& population, double(*fitnessFunc)(const vector<int>&)) {
for (int i = 0; i < population.size(); ++i) {
population[i].fitness = fitnessFunc(population[i].genes);
}
}
//选择
vector<Individual> selection(vector<Individual>& population, int eliteSize) {
vector<Individual> matingPool;
sort(population.begin(), population.end(), [](const Individual& a, const Individual& b) {
return a.fitness > b.fitness;
});
for (int i = 0; i < eliteSize; ++i) {
matingPool.push_back(population[i]);
}
random_device rd;
mt19937 gen(rd());
uniform_real_distribution<> dis(0, 1);
double totalFitness = accumulate(population.begin(), population.end(), 0.0, [](double sum, const Individual& ind) {
return sum + ind.fitness;
});
for (int i = 0; i < population.size() - eliteSize; ++i) {
double r = dis(gen) * totalFitness;
double sum = 0;
for (int j = 0; j < population.size(); ++j) {
sum += population[j].fitness;
if (sum >= r) {
matingPool.push_back(population[j]);
break;
}
}
}
return matingPool;
}
//交叉
void crossover(vector<Individual>& matingPool, int eliteSize) {
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<> dis(0, matingPool[0].genes.size() - 1);
for (int i = eliteSize; i < matingPool.size(); i += 2) {
int point = dis(gen);
for (int j = point; j < matingPool[i].genes.size(); ++j) {
swap(matingPool[i].genes[j], matingPool[i + 1].genes[j]);
}
}
}
//变异
void mutation(vector<Individual>& matingPool, double mutationRate, int eliteSize) {
random_device rd;
mt19937 gen(rd());
uniform_real_distribution<> dis(0, 1);
for (int i = eliteSize; i < matingPool.size(); ++i) {
for (int j = 0; j < matingPool[i].genes.size(); ++j) {
if (dis(gen) < mutationRate) {
matingPool[i].genes[j] = 1 - matingPool[i].genes[j];
}
}
}
}
//遗传算法
vector<int> geneticAlgorithm(double(*fitnessFunc)(const vector<int>&), int geneLength, int populationSize, int eliteSize, double mutationRate, int generations) {
vector<Individual> population = initializePopulation(populationSize, geneLength);
for (int i = 0; i < generations; ++i) {
calculateFitness(population, fitnessFunc);
vector<Individual> matingPool = selection(population, eliteSize);
crossover(matingPool, eliteSize);
mutation(matingPool, mutationRate, eliteSize);
population = matingPool;
}
sort(population.begin(), population.end(), [](const Individual& a, const Individual& b) {
return a.fitness > b.fitness;
});
return population[0].genes;
}
//适应度函数示例
double fitnessFunction(const vector<int>& genes) {
double sum = accumulate(genes.begin(), genes.end(), 0.0);
return sum / genes.size();
}
int main() {
vector<int> result = geneticAlgorithm(fitnessFunction, 10, 100, 10, 0.1, 100);
for (int i = 0; i < result.size(); ++i) {
cout << result[i] << " ";
}
cout << endl;
return 0;
}
```
在这个实现中,我们定义了一个`Individual`结构体,表示一个个体,包括基因序列和适应度。`initializePopulation()`函数用于初始化种群,`calculateFitness()`函数用于计算适应度,`selection()`函数用于选择,`crossover()`函数用于交叉,`mutation()`函数用于变异,`geneticAlgorithm()`函数用于整个遗传算法的流程。在`main()`函数中,我们使用`geneticAlgorithm()`函数来解决一个简单的问题。适应度函数`fitnessFunction()`的定义可以根据具体问题进行修改。
帮我用C++写段遗传算法代码
好的,我可以为您提供一些遗传算法的代码示例,以下是一个简单的遗传算法实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define POP_SIZE 10
#define CHROMO_SIZE 10
#define MUTATION_RATE 0.1
#define CROSSOVER_RATE 0.7
typedef struct {
int genes[CHROMO_SIZE];
int fitness;
} Chromosome;
Chromosome population[POP_SIZE];
int generation = 0;
int random_int(int min, int max) {
return rand() % (max - min + 1) + min;
}
void init_population() {
int i, j;
for (i = 0; i < POP_SIZE; i++) {
for (j = 0; j < CHROMO_SIZE; j++) {
population[i].genes[j] = random_int(0, 1);
}
population[i].fitness = 0;
}
}
int evaluate_fitness(Chromosome *chromo) {
int i, fitness = 0;
for (i = 0; i < CHROMO_SIZE; i++) {
fitness += chromo->genes[i];
}
return fitness;
}
void evaluate_population() {
int i;
for (i = 0; i < POP_SIZE; i++) {
population[i].fitness = evaluate_fitness(&population[i]);
}
}
void print_chromosome(Chromosome *chromo) {
int i;
for (i = 0; i < CHROMO_SIZE; i++) {
printf("%d", chromo->genes[i]);
}
printf(" (%d)\n", chromo->fitness);
}
void print_population() {
int i;
for (i = 0; i < POP_SIZE; i++) {
print_chromosome(&population[i]);
}
}
void mutate(Chromosome *chromo) {
int i;
for (i = 0; i < CHROMO_SIZE; i++) {
if ((double)rand() / RAND_MAX < MUTATION_RATE) {
chromo->genes[i] = !chromo->genes[i];
}
}
}
void crossover(Chromosome *parent1, Chromosome *parent2, Chromosome *child1, Chromosome *child2) {
int i, crossover_point;
crossover_point = random_int(1, CHROMO_SIZE - 1);
for (i = 0; i < crossover_point; i++) {
child1->genes[i] = parent1->genes[i];
child2->genes[i] = parent2->genes[i];
}
for (i = crossover_point; i < CHROMO_SIZE; i++) {
child1->genes[i] = parent2->genes[i];
child2->genes[i] = parent1->genes[i];
}
}
void select_parents(Chromosome **parent1, Chromosome **parent2) {
int i, total_fitness = 0, r1, r2;
for (i = 0; i < POP_SIZE; i++) {
total_fitness += population[i].fitness;
}
r1 = random_int(0, total_fitness - 1);
r2 = random_int(0, total_fitness - 1);
for (i = 0; i < POP_SIZE; i++) {
r1 -= population[i].fitness;
if (r1 < 0) {
*parent1 = &population[i];
break;
}
}
for (i = 0; i < POP_SIZE; i++) {
r2 -= population[i].fitness;
if (r2 < 0) {
*parent2 = &population[i];
break;
}
}
}
void evolve() {
int i;
Chromosome *parent1, *parent2, child1, child2;
for (i = 0; i < POP_SIZE / 2; i++) {
select_parents(&parent1, &parent2);
crossover(parent1, parent2, &child1, &child2);
mutate(&child1);
mutate(&child2);
population[i * 2] = child1;
population[i * 2 + 1] = child2;
}
evaluate_population();
generation++;
}
int main() {
srand(time(NULL));
init_population();
evaluate_population();
while (generation < 100) {
printf("Generation %d:\n", generation);
print_population();
evolve();
}
return 0;
}
```
这是一个简单的二进制遗传算法实现,用于求解一个二进制字符串中1的个数最大的问题。您可以根据自己的需求进行修改和扩展。
阅读全文