📄 population.cpp
字号:
#include "stdafx.h"
#include "population.h"
#include "chromosome.h"
#include "myRandom.h"
extern MyRandom myRandom;
Population::Population(int popsize) {
this->PopSize = popsize;
this->AvgFit = 0 ;
this->Best =0;
this->MaxFit =0;
this->MinFit =0;
chromosomes = new Chromosome[PopSize ];
MatingPool = new int [PopSize ];
}
Population::Population(Population &pop) {
this->AvgFit =pop.get_avgfit ();
this->Best =pop.get_best ();
this->MaxFit = pop.get_maxfit ();
this->MinFit = pop.get_minfit ();
chromosomes = new Chromosome[PopSize ];
MatingPool = new int [PopSize ];
for(int i=0;i< PopSize;i++)
{
chromosomes[i].copyGene(pop.chromosomes [i].myGenes ,PopSize,0);
MatingPool[i] = pop.MatingPool[i];
}
}
Population::~Population (){
delete [] chromosomes;
delete [] MatingPool;
}
void Population::evaluate() {
for(int i=0;i<PopSize;i++)
chromosomes[i].evaluate ();
int index_best = 0 ;
double fit_sum = 0.0 ;
double max_fit = chromosomes[0].get_fitness () ;
double min_fit = chromosomes[0].get_fitness () ;
for(int i=0;i<PopSize;i++)
{
fit_sum = fit_sum + chromosomes[i].get_fitness();
if(max_fit<chromosomes[i].get_fitness()){
index_best = i ;
max_fit=chromosomes[i].get_fitness ();
}
if(min_fit>chromosomes[i].get_fitness ())
min_fit = chromosomes[i].get_fitness ();
}
this->Best = index_best ;
this->MaxFit = max_fit;
this->MinFit = min_fit;
this->AvgFit = fit_sum/(double)PopSize;
}
//赌轮选择
void Population::selection() {
double fit_sum = 0.0;
double mid_fit_sum = 0.0;
double rand_data = 0.0 ;
int j;
for(int i=0;i<PopSize;i++)
fit_sum = fit_sum + chromosomes[i].get_fitness();
for(int i=0;i<PopSize;i++)
{
rand_data = myRandom.ddouble_random(fit_sum);
mid_fit_sum = 0.0;
for(j=0;j<PopSize;j++)
{
mid_fit_sum = mid_fit_sum + chromosomes[j].get_fitness ();
if( mid_fit_sum >= rand_data )
break;
}
MatingPool[i] = j;
}
}
//锦标赛选择
#define theCollect 7
void Population::tournamentSeclection (){
////int theCollect = 7 ; //随机选取 theCollect 个个体
int collection[theCollect]; //存储选择的个个体的编号
int count = 0;
double mid_fit =0.0;
for(int i=0;i<theCollect;i++)
collection[i] = 0 ;
for(int i =0;i<PopSize; i++)
{
for(int j =0;j< theCollect ;j++)
collection[j] = myRandom.lim_int_random (0,PopSize);
count = collection[0];
mid_fit =chromosomes[collection[0]].get_fitness();
for(int j = 0;j< theCollect;j++)
{
if(mid_fit < chromosomes[collection[j]].get_fitness ())
{
mid_fit = chromosomes[collection[j]].get_fitness () ;
count = collection[j];
}
}
MatingPool[i] = count ;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -