前言:
本文记录了自己在智能算法课程作业的实现代码设计,简单实现了遗传算法,所有代码为自己梳理了算法流程之后原创实现的!!!仅供参考,如果觉得有任何问题可以留言讨论~
别人的代码可以参考一些关键环节的实现,但是整体的框架设计以及具体实现还是要自己动手完成才有意义!!
另附
在查资料阶段参考的比较好的相关博客文章分享如下:
算法流程理解
c++实现参考
C++实现参考2
问题描述:
遗传算法实现流程
一、程序设计
1、辅助类设计
A)个体类
通过类成员函数以及构造函数,实现个体的编码与适应值计算等
class Individual {
public:
double x;
double y;
vector<int>code;
double fitness;
double FitRatio;
void init() {
for (int i = 0; i < Len; i++) {
double r = rand();
int x = (r < RAND_MAX / 2) ? 0 : 1;
code.push_back(x);
}
}
double GetFitness() {
return fitness = f(x, y);
}
void decode() {
double ansX = 0, ansY = 0;
for (int i = 0; i < LenX1; i++)
ansX = ansX * 2 + code[i];
for (int i = LenX1; i < Len; i++)
ansY = ansY * 2 + code[i];
x = xl + (xr - xl) * ansX / (pow(2, LenX1) - 1);
y = yl + (yr - yl) * ansY / (pow(2, LenX2) - 1);
}
Individual() {
init();
decode();
GetFitness();
FitRatio = 0;
}
};
B) 种群类
通过类成员函数以及将个体类对象作为成员,实现种群的初始化,以及选择交叉变异等一系列操作等
class Group {
public:
vector<Individual*>Current;
vector<Individual*>Next;
int CBestNo;
double CBestVal; int NBestNo;
double NBestVal;
Group() {
CBestNo = -1;
NBestNo = -1;
NBestVal = -100;
CBestVal = -100;
double sum = 0; CBestVal = -100;
for (int i = 0; i < N; i++) {
Individual* p = new Individual();
double tem = p->fitness;
sum += tem;
if (tem > CBestVal) {
CBestNo = i; CBestVal = tem;
}
Current.push_back(p);
}
for (int i = 0; i < N; i++)
Current[i]->FitRatio = Current[i]->fitness / sum;
}
void Selection() {
for (int i = 0; i < N; i++) {
int n = 0;
double pos = ran(seed);
double CheckPos = 0;
while (1) {
CheckPos += Current[n]->FitRatio;
if (CheckPos >= pos)break;
n++;
}
Next.push_back(Current[n]);
}
}
void Cross() {
vector<Individual*>Participants;
for (int i = 0; i < N; i++) {
if (ran(seed) < Pcross)Participants.push_back(Next[i]);
}
int num = Participants.size();
for (int i = 1; i < num; i += 2) {
int dot = (rand() / RAND_MAX) *Len;
int tem;
for (int j = 0; j < dot; j++) {
tem = Participants[i - 1]->code[j];
Participants[i - 1]->code[j] = Participants[i]->code[j];
Participants[i]->code[j] = tem;
}
}
}
void Mutate<