/* 本程序试用遗传算法来解决 Rosenbrock 函数的全局最大值计算问题:
max f(x1,x2) = 100 (x1^2-x2)^2 + (1-x1)^2
s.t. -2.048 ≤ xi ≤ 2.048 (i=1,2)*/
#include<iostream>
#include<time.h>
#include <stdlib.h>
#include<cmath>
using namespace std;
const int M=80,T=100; // M 群体大小,pc 交叉概率,pm 变异概率,T 终止代数
const double pc=0.6,pm=0.01;
struct population //定义群体结构
{int x[20];
double x1,x2;
double fit;
double sumfit;
}p[M];
void initial(population *); //初始化函数
void evaluefitness(population *); // 计算适应度
void select(population *); // 选择复制函数
void crossover(population *); // 交叉函数
void mutation(population *); // 变异函数
void decoding(population *); // 解码函数
void print(population *); //显示函数
int main() //遗传算法主函数
{int gen=0;
initial(&p[0]); //随机获得初始解
cout<<"initialed!"<<endl;
print(&p[0]);
decoding(&p[0]); //先解码
cout<<"decoded!"<<endl;
print(&p[0]);
evaluefitness(&p[0]); //计算适应值与累计适值
cout<<"evalued!"<<endl;
print(&p[0]);
while(gen<=T)
{cout<<"gen="<<gen+1<<endl;
select(&p[0]);
decoding(&p[0]);