您好,登錄后才能下訂單哦!
在C++中實現遺傳算法,通常會使用STL庫提供的數據結構和算法來實現遺傳算法的各個步驟,比如選擇、交叉、變異等。以下是一個簡單的C++遺傳算法實現示例:
#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
#include <ctime>
using namespace std;
const int POPULATION_SIZE = 10;
const int GENOME_SIZE = 5;
const int MAX_GENERATION = 100;
const double CROSSOVER_RATE = 0.7;
const double MUTATION_RATE = 0.1;
// 個體結構體
struct Individual {
vector<int> genome;
int fitness;
};
// 隨機生成一個個體
Individual generateIndividual() {
Individual ind;
for (int i = 0; i < GENOME_SIZE; ++i) {
ind.genome.push_back(rand() % 2);
}
return ind;
}
// 計算個體的適應度
int calcFitness(const Individual& ind) {
int fitness = 0;
for (int gene : ind.genome) {
fitness += gene;
}
return fitness;
}
// 選擇操作
vector<Individual> selection(const vector<Individual>& population) {
vector<Individual> newPopulation;
newPopulation.reserve(POPULATION_SIZE);
for (int i = 0; i < POPULATION_SIZE; ++i) {
int idx1 = rand() % POPULATION_SIZE;
int idx2 = rand() % POPULATION_SIZE;
if (population[idx1].fitness > population[idx2].fitness) {
newPopulation.push_back(population[idx1]);
} else {
newPopulation.push_back(population[idx2]);
}
}
return newPopulation;
}
// 交叉操作
void crossover(vector<Individual>& population) {
for (int i = 0; i < POPULATION_SIZE; i += 2) {
if ((double)rand() / RAND_MAX < CROSSOVER_RATE) {
int crossoverPoint = rand() % GENOME_SIZE;
for (int j = crossoverPoint; j < GENOME_SIZE; ++j) {
swap(population[i].genome[j], population[i + 1].genome[j]);
}
}
}
}
// 變異操作
void mutation(vector<Individual>& population) {
for (Individual& ind : population) {
for (int i = 0; i < GENOME_SIZE; ++i) {
if ((double)rand() / RAND_MAX < MUTATION_RATE) {
ind.genome[i] = 1 - ind.genome[i];
}
}
}
}
int main() {
srand(time(NULL));
vector<Individual> population;
for (int i = 0; i < POPULATION_SIZE; ++i) {
population.push_back(generateIndividual());
}
for (int generation = 0; generation < MAX_GENERATION; ++generation) {
for (Individual& ind : population) {
ind.fitness = calcFitness(ind);
}
sort(population.begin(), population.end(), [](const Individual& a, const Individual& b) {
return a.fitness > b.fitness;
});
cout << "Generation " << generation << " Best fitness: " << population[0].fitness << endl;
population = selection(population);
crossover(population);
mutation(population);
}
cout << "Best individual: ";
for (int gene : population[0].genome) {
cout << gene << " ";
}
cout << endl;
return 0;
}
上面的代碼實現了一個簡單的遺傳算法,并且使用隨機生成的二進制基因組來演示遺傳算法的選擇、交叉和變異操作。在實際項目中,可以根據具體的問題領域和需求對遺傳算法進行進一步的優化和擴展。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。