GVKun编程网logo

在遗传算法中为多个“推销员” TSP实现交叉功能(遗传算法中每个被选中的个体,一定会进行交叉操作)

16

如果您想了解在遗传算法中为多个“推销员”TSP实现交叉功能和遗传算法中每个被选中的个体,一定会进行交叉操作的知识,那么本篇文章将是您的不二之选。我们将深入剖析在遗传算法中为多个“推销员”TSP实现交叉

如果您想了解在遗传算法中为多个“推销员” TSP实现交叉功能遗传算法中每个被选中的个体,一定会进行交叉操作的知识,那么本篇文章将是您的不二之选。我们将深入剖析在遗传算法中为多个“推销员” TSP实现交叉功能的各个方面,并为您解答遗传算法中每个被选中的个体,一定会进行交叉操作的疑在这篇文章中,我们将为您介绍在遗传算法中为多个“推销员” TSP实现交叉功能的相关知识,同时也会详细的解释遗传算法中每个被选中的个体,一定会进行交叉操作的运用方法,并给出实际的案例分析,希望能帮助到您!

本文目录一览:

在遗传算法中为多个“推销员” TSP实现交叉功能(遗传算法中每个被选中的个体,一定会进行交叉操作)

在遗传算法中为多个“推销员” TSP实现交叉功能(遗传算法中每个被选中的个体,一定会进行交叉操作)

采用略有不同的方法解决了此问题。我没有在执行交叉操作之前拆分一系列航点,而只是传递了一系列航点

[0,1,2,3,4,5,6,7,8,9,10,11] 

进行交叉,并在计算每个集合的适用性时,我根据m无人机划分航路点,并找到每一代的最佳解决方案。新的分频器功能如下:

DNA DNA::crossover( DNA &parentB)
{

    int start = rand () % (this->getOrder().size()-1);
    int end =  getRandomInt<std::size_t>(start +1,this->getOrder().size()-1);

    std::vector<std::size_t>::const_iterator first = this->getOrder().begin() + start;
    std::vector<std::size_t>::const_iterator second = this->getOrder().begin() + end;

     std::vector<std::size_t> newOrder(first,second);

     for(std::size_t i = 0; i < parentB.getOrder().size(); i++)
      {
          int city = parentB.getOrder().at(i);
          if(std::find(newOrder.begin(),newOrder.end(),city) == newOrder.end())
          {
              newOrder.push_back(city);
          }
      }

    return DNA(newOrder,waypoints,number_of_drones);

}

c# – 用于TSP的遗传算法中的Сrossover操作

c# – 用于TSP的遗传算法中的Сrossover操作

我试图用 Genetic algorithm解决 Travelling Salesman Problem (TSP)

我的基因组是图中顶点的排列(Salesman的路径).

我应该如何在我的基因组上进行交叉操作?

在哪里可以找到C#中我的问题的实现?

解决方法

您应该检查Gokturk Ucoluk的“遗传算法解决TSP避免特殊交叉和突变”. PDF here.它给出了用于排列的特殊交叉运算符的概述,并提出了一种在标准交叉中工作良好的排列的巧妙表示(即跨越两个排列总是产生两个排列).

关键的洞察是将排列表示为其反转序列,即,对于每个元素i,存储在[i]中,在排列中i比在i左侧多少个元素.与直接表示不同,对于[i]的唯一约束是局部的,即[i]不能大于N-i.这意味着两个有效反转序列的简单交叉总是产生两个有效的反转序列 – 不需要特殊处理重复元素.

c# – 遗传算法中的比赛评估

c# – 遗传算法中的比赛评估

现在,每个遗传C#库(A.Forge,genetic Algorithm Framework,geneticSharp)似乎只评估一个染色体,然后使用各种选择方法之一来创建新一代.

由于我的问题涉及到两个认知相互作用,所以单独评估自己的健身状况有点困难.虽然游戏很简单,可以创建一些表面的障碍(AI不直接交互,但障碍被发送给每个其他游戏),这将允许我获得一些抽象的健身,但这不会是“真正的”交易.

图书馆也似乎没有提供另一个接口,我可以实现这样的评估方法.是否有其他框架允许这个或者我需要从头开始?

解决方法

每个遗传算法库应该有一些方法来定义一个适合度函数,这是真正的你正在寻找的. AForge.NET公开了 IFitnessFunction界面. geneticSharp公开了 IFitness界面.是的,您必须自己编写健身功能 – 这是您的问题区域唯一的部分.你可以使它像你想要的那样简单或复杂.

在每个染色体通过适应度功能并分配一个分数后,系统使用您喜欢的任何选择标准(锦标赛,轮盘赌等)来选择通过交叉和/或突变进入下一代的染色体.

所以而不是像这样流程:

>匹配当代染色体
每条染色体对都发生一轮
获奖者创造下一代

遗传算法的工作原理如下:

每个染色体都发生一轮并得分
>选择算法使用该分数来挑选总体获胜者
获奖者创造下一代

实质上,每个染色体已经与其他染色体竞争,只比您更抽象一步,我会玩一个游戏.

您可能会采用健身功能,将当前人口中随机的其他成员作为对手.更好的是使用上一代最好的染色体作为整个当代的对手.

分配点到您的染色体进一步进行游戏和奖励积分为对手产生障碍(如果这是独特的动作,与游戏中的正常游戏分开).返回染色体的最终得分作为适应度函数输出.

C++实现简单遗传算法

C++实现简单遗传算法

本文实例讲述了C++实现简单遗传算法。分享给大家供大家参考。具体实现方法如下:

//遗传算法 GA 
#include<iostream>
#include <cstdlib>
#include<bitset>
using namespace std;
const int L=5; //定义编码的长度 
int f(int x) //定义测设函数f(x) 
{
int result;
result=x*x*x-60*x*x+900*x+100;
return result;
}
int main(int argc,char *argv[])
{
int a(0),b(32); //定义x的定义域范围
const int pop_size=8; //定义种群大小
// int L; //指定编码的长度 
const int NG=20; //指定种群最大的繁殖的代数 
int t=0; //当前繁殖的代数 
int p[pop_size]; //定义种群 
int q[pop_size]; //定义繁殖种群 即种群的下一代 
srand(6553); //定义随机数生成的种子 
double sum; //适值总和 
double avl_sum; //适度平均值 
double p_probability[pop_size]; //适值概率 
double pp[pop_size];
double pro; //定义随机生成的概率 
float pc=0.90; //定义交叉的概率 
float pm=0.05; //定义变异的概率 
cout<<"初始的种群 "; 
for(int i=0;i<pop_size;i++) //生成初始的第0代种群 
  {
p[i]=rand()%31;
cout<<p[i]<<" ";
  }
   cout<<endl;
   cout<<endl;
   void Xover(int &,int &); //声明交叉函数 
//当停止准则不满足 即繁殖代数没到最大代数,继续繁殖
while(t<=NG)             
{ 
cout<<"繁殖的代数:t="<<t<<endl;
sum=0.0;
for(int i=0;i<pop_size;i++)      
  {
q[i]=p[i];
cout<<q[i]<<" ";
  }
  cout<<endl;
 for(int i=0;i<pop_size;i++) //计算sum 
   sum +=f(p[i]);
 avl_sum=sum/pop_size;
 cout<<"sum="<<sum<<endl;
 cout<<"适度平均值="<<avl_sum<<endl; 
    for(int i=0;i<pop_size;i++) //计算适值概率 
    {
      p_probability[i]=f(p[i])/sum;
if(i==0)
{
pp[i]=p_probability[i];
cout<<"pp"<<i<<"="<<pp[i]<<endl;
}
      else
      {
       pp[i]=p_probability[i]+pp[i-1];
    cout<<"pp"<<i<<"="<<pp[i]<<endl;
      }
//cout<<"p_probability"<<i<<"="<<p_probability[i]<<endl;
    }
    //选择双亲
     for(int i=0;i<pop_size;i++) 
     {
     pro=rand()%1000/1000.0;
if(pro>=pp[0]&&pro<pp[1])
  p[i]=q[0]; 
else if(pro>=pp[1]&&pro<pp[2])
       p[i]=q[1];
     else if(pro>=pp[2]&&pro<pp[3])
       p[i]=q[2];
     else if(pro>=pp[3]&&pro<pp[4])
       p[i]=q[3];
     else if(pro>=pp[4]&&pro<pp[5])
       p[i]=q[4];
     else 
       p[i]=q[5]; 
     }
//杂交算子
int r=0;
int z=0; 
for(int j=0;j<pop_size;j++) 
{
  pro=rand()%1000/1000.0;
if(pro<pc)
{
 ++z;
 if(z%2==0)
  Xover(p[r],p[j]);
 else
  r=j; 
} 
} 
//变异算子 
for(int i=1;i<=pop_size;i++)
 for(int j=0;j<L;j++)
{
 pro=rand()%1000/1000.0; //在【0,1】区间产生随机数
if(pro<pm)
{
bitset<L>v(p[i]);      
v.flip(j);
p[i]=v.to_ulong();
} 
 } 
t++;
cout<<endl; //种群繁殖一代 
 }
 cout<<"最终结果:";  
 for(int i(0);i<pop_size;i++) //算法结束,输出结果 
  {
 cout<<p[i]<<" ";
  }
  cout<<endl;
return 0;
}
//定义杂交操作 
 void Xover(int &a,int &b)         
{ 
int pos; //随机生成杂交点 即第几个分量进行相互交换
pos=rand()%5+1; //在n个分量中,随机确定第pos个分量 
int j,k;
  j=pos;
  k=pos;
bitset<L>e(a);
bitset<L>f(b); //前pos个分量进行相互交换
bitset<L>g;            
bitset<L>h;
for(int i=0;i<pos;i++)
{
if(e[i]==1)
 g.set(i); 
   }
  for(int i=0;i<pos;i++)
   {
   if(f[i]==1)
    h.set(i);
   }
  for(j;j<L;j++)
   {
   if(f[j]==1)
    g.set(j);
   }
  for(k;k<L;k++)
   {
   if(e[k]==1)
    h.set(k);
   }
a=g.to_ulong();
b=h.to_ulong();  
}

希望本文所述对大家的C++程序设计有所帮助。

C++实现遗传算法

C++实现遗传算法

本文实例讲述了C++实现简单遗传算法。分享给大家供大家参考。具体实现方法如下:

// CMVSOGA.h : main header file for the CMVSOGA.cpp
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
 
#if !defined(AFX_CMVSOGA_H__45BECA_61EB_4A0E_9746_9A94D1CCF767__INCLUDED_)
#define AFX_CMVSOGA_H__45BECA_61EB_4A0E_9746_9A94D1CCF767__INCLUDED_
 
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "Afxtempl.h"
#define variablenum 14
class CMVSOGA
{
public:
 CMVSOGA();
 ~CMVSOGA();
 void selectionoperator();
 void crossoveroperator();
 void mutationoperator();
 void initialpopulation(int,int,double,double *,double *);      //种群初始化
 void generatenextpopulation();     //生成下一代种群
 void evaluatepopulation();      //评价个体,求最佳个体
 void calculateobjectvalue();     //计算目标函数值
 void calculatefitnessvalue();     //计算适应度函数值
 void findbestandworstindividual();     //寻找最佳个体和最差个体
 void performevolution();  
 void GetResult(double *);
 void GetPopData(CList <double,double>&);
 void SetfitnessData(CList <double,double>&,CList <double,double>&);
private:
 struct individual
 {
 double chromosome[variablenum];     //染色体编码长度应该为变量的个数
 double value;     
 double fitness;       //适应度
 };
 double variabletop[variablenum];     //变量值
 double variablebottom[variablenum];     //变量值
 int popsize;       //种群大小
// int generation;       //世代数
 int best_index; 
 int worst_index;
 double crossoverrate;      //交叉率
 double mutationrate;      //变异率
 int maxgeneration;       //最大世代数
 struct individual bestindividual;     //最佳个体
 struct individual worstindividual;     //最差个体
 struct individual current;       //当前个体
 struct individual current1;       //当前个体
 struct individual currentbest;     //当前最佳个体
 CList <struct individual,struct individual &> population;  //种群
 CList <struct individual,struct individual &> newpopulation; //新种群
 CList <double,double> cfitness;     //存储适应度值
 //怎样使链表的数据是一个结构体????主要是想把种群作成链表。节省空间。
};
#endif
 
 
 
执行文件:
 
// CMVSOGA.cpp : implementation file
//
 
#include "stdafx.h"
//#include "vld.h"
#include "CMVSOGA.h"
#include "math.h"
#include "stdlib.h"
 
 
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CMVSOGA.cpp
CMVSOGA::CMVSOGA()
{
 best_index=0; 
 worst_index=0;
 crossoverrate=0;      //交叉率
 mutationrate=0;      //变异率
 maxgeneration=0;
}
CMVSOGA::~CMVSOGA()
{
 best_index=0; 
 worst_index=0;
 crossoverrate=0;      //交叉率
 mutationrate=0;      //变异率
 maxgeneration=0;
 population.RemoveAll();  //种群
 newpopulation.RemoveAll(); //新种群
 cfitness.RemoveAll(); 
}
void CMVSOGA::initialpopulation(int ps,int gen,double cr,double mr,double *xtop,double *xbottom) //第一步,初始化。
{
 //应该采用一定的策略来保证遗传算法的初始化合理,采用产生正态分布随机数初始化?选定中心点为多少?
 int i,j;
 popsize=ps;
 maxgeneration=gen;
 crossoverrate=cr;
 mutationrate =mr;
 for (i=0;i<variablenum;i++)
 {
 variabletop[i] =xtop[i];
 variablebottom[i] =xbottom[i];
 }
 //srand( (unsigned)time( NULL ) ); //寻找一个真正的随机数生成函数。
 for(i=0;i<popsize;i++)
 { 
 for (j=0;j<variablenum ;j++)
 {
  current.chromosome[j]=double(rand()%10000)/10000*(variabletop[j]-variablebottom[j])+variablebottom[j];
 }
 current.fitness=0;
 current.value=0;
 population.InsertAfter(population.Findindex(i),current);//除了初始化使用insertafter外,其他的用setat命令。
 }
}
void CMVSOGA::generatenextpopulation()//第三步,生成下一代。
{
 //srand( (unsigned)time( NULL ) );
 selectionoperator();
 crossoveroperator();
 mutationoperator();
}
//void CMVSOGA::evaluatepopulation()  //第二步,评价个体,求最佳个体
//{
// calculateobjectvalue();
// calculatefitnessvalue();  //在此步中因该按适应度值进行排序.链表的排序.
// findbestandworstindividual();
//}
void CMVSOGA:: calculateobjectvalue() //计算函数值,应该由外部函数实现。主要因为目标函数很复杂。
{
 int i,j;
  double x[variablenum];
 for (i=0; i<popsize; i++)
 {
 current=population.GetAt(population.Findindex(i)); 
 current.value=0;
 //使用外部函数进行,在此只做结果的传递。
 for (j=0;j<variablenum;j++)
 {
  x[j]=current.chromosome[j];
  current.value=current.value+(j+1)*pow(x[j],4);
 }
 ////使用外部函数进行,在此只做结果的传递。
 population.SetAt(population.Findindex(i),current);
 }
}
 
void CMVSOGA::mutationoperator() //对于浮点数编码,变异算子的选择具有决定意义。
     //需要guass正态分布函数,生成方差为sigma,均值为浮点数编码值c。
{
// srand((unsigned int) time (NULL));
 int i,j;
 double r1,r2,p,sigma;//sigma高斯变异参数
 
 for (i=0;i<popsize;i++)
 {
 current=population.GetAt(population.Findindex(i));
 
 //生成均值为current.chromosome,方差为sigma的高斯分布数
 for(j=0; j<variablenum; j++)
 {  
  r1 = double(rand()%10001)/10000;
  r2 = double(rand()%10001)/10000;
  p = double(rand()%10000)/10000;
  if(p<mutationrate)
  {
  double sign;
  sign=rand()%2;
  sigma=0.01*(variabletop[j]-variablebottom [j]);
  //高斯变异
  if(sign)
  {
   current.chromosome[j] = (current.chromosome[j] 
   + sigma*sqrt(-2*log(r1)/0.4323)*sin(2*3.1415926*r2));
  }
  else
  {
   current.chromosome[j] = (current.chromosome[j] 
   - sigma*sqrt(-2*log(r1)/0.4323)*sin(2*3.1415926*r2));
  }
  if (current.chromosome[j]>variabletop[j])
  {
   current.chromosome[j]=double(rand()%10000)/10000*(variabletop[j]-variablebottom[j])+variablebottom[j];
  }
  if (current.chromosome[j]<variablebottom [j])
  {
   current.chromosome[j]=double(rand()%10000)/10000*(variabletop[j]-variablebottom[j])+variablebottom[j];
  }
  }
 }
 population.SetAt(population.Findindex(i),current);
 }
}
void CMVSOGA::selectionoperator()  //从当前个体中按概率选择新种群,应该加一个复制选择,提高种群的平均适应度
{
 int i,j,pindex=0;
 double p,pc,sum;
 i=0;
 j=0;
 pindex=0;
 p=0;
 pc=0;
 sum=0.001;
 newpopulation.RemoveAll();
 cfitness.RemoveAll();
 //链表排序
// population.SetAt (population.Findindex(0),current); //多余代码
 for (i=1;i<popsize;i++)
 { 
 current=population.GetAt(population.Findindex(i));
 for(j=0;j<i;j++)  //从小到大用before排列。
 {
  current1=population.GetAt(population.Findindex(j));//临时借用变量
  if(current.fitness<=current1.fitness) 
  {
  population.InsertBefore(population.Findindex(j),current);
  population.RemoveAt(population.Findindex(i+1));
  break;
  }
 }
// m=population.GetCount();
 }
 //链表排序
 for(i=0;i<popsize;i++)//求适应度总值,以便归一化,是已经排序好的链。
 {
 current=population.GetAt(population.Findindex(i)); //取出来的值出现问题.
 sum+=current.fitness;
 }
 for(i=0;i<popsize; i++)//归一化
 {
 current=population.GetAt(population.Findindex(i)); //population 有值,为什么取出来的不正确呢??
 current.fitness=current.fitness/sum;
 cfitness.InsertAfter (cfitness .Findindex(i),current.fitness);
 }
 
 for(i=1;i<popsize; i++)//概率值从小到大;
 {
 current.fitness=cfitness.GetAt (cfitness.Findindex(i-1))
  +cfitness.GetAt(cfitness.Findindex(i));  //归一化
 cfitness.SetAt (cfitness .Findindex(i),current.fitness);
 population.SetAt(population.Findindex(i),current);
 }
 for (i=0;i<popsize;)//轮盘赌概率选择。本段还有问题。
 {
 p=double(rand()%999)/1000+0.0001; //随机生成概率
 pindex=0; //遍历索引
 pc=cfitness.GetAt(cfitness.Findindex(1)); //为什么取不到数值???20060910
 while(p>=pc&&pindex<popsize) //问题所在。
 {
  pc=cfitness.GetAt(cfitness .Findindex(pindex));
  pindex++;
 }
 //必须是从index~popsize,选择高概率的数。即大于概率p的数应该被选择,选择不满则进行下次选择。
 for (j=popsize-1;j<pindex&&i<popsize;j--)
 {
  newpopulation.InsertAfter (newpopulation.Findindex(0),population.GetAt (population.Findindex(j)));
  i++;
 }
 }
 for(i=0;i<popsize; i++)
 {
 population.SetAt (population.Findindex(i),newpopulation.GetAt (newpopulation.Findindex(i)));
 }
// j=newpopulation.GetCount();
// j=population.GetCount();
 newpopulation.RemoveAll();
}
 
//current  变化后,以上没有问题了。
 
 
void CMVSOGA:: crossoveroperator()  //非均匀算术线性交叉,浮点数适用,alpha,beta是(0,1)之间的随机数
     //对种群中两两交叉的个体选择也是随机选择的。也可取beta=1-alpha;
     //current的变化会有一些改变。
{
 int i,j;
 double alpha,beta;
 CList <int,int> index;
 int point,temp;
 double p;
// srand( (unsigned)time( NULL ) );
 for (i=0;i<popsize;i++)//生成序号
 {
 index.InsertAfter (index.Findindex(i),i);
 }
 for (i=0;i<popsize;i++)//打乱序号
 {
 point=rand()%(popsize-1);
 temp=index.GetAt(index.Findindex(i));
 index.SetAt(index.Findindex(i),index.GetAt(index.Findindex(point))); 
 index.SetAt(index.Findindex(point),temp);
 }
 for (i=0;i<popsize-1;i+=2)
 {//按顺序序号,按序号选择两个母体进行交叉操作。
 p=double(rand()%10000)/10000.0;
 if (p<crossoverrate)
 {  
  alpha=double(rand()%10000)/10000.0;
  beta=double(rand()%10000)/10000.0;
  current=population.GetAt(population.Findindex(index.GetAt(index.Findindex(i))));
  current1=population.GetAt(population.Findindex(index.GetAt(index.Findindex(i+1))));//临时使用current1代替
  for(j=0;j<variablenum;j++)
  { 
  //交叉
  double sign;
  sign=rand()%2;
  if(sign)
  {
   current.chromosome[j]=(1-alpha)*current.chromosome[j]+
   beta*current1.chromosome[j];
  }
  else
  {
   current.chromosome[j]=(1-alpha)*current.chromosome[j]-
   beta*current1.chromosome[j];
  }
  if (current.chromosome[j]>variabletop[j]) //判断是否超界.
  {
   current.chromosome[j]=double(rand()%10000)/10000*(variabletop[j]-variablebottom[j])+variablebottom[j];
  }
  if (current.chromosome[j]<variablebottom [j])
  {
   current.chromosome[j]=double(rand()%10000)/10000*(variabletop[j]-variablebottom[j])+variablebottom[j];
  }
  if(sign)
  {
   current1.chromosome[j]=alpha*current.chromosome[j]+
   (1- beta)*current1.chromosome[j];
  }
  else
  {
   current1.chromosome[j]=alpha*current.chromosome[j]-
   (1- beta)*current1.chromosome[j];
  }
  if (current1.chromosome[j]>variabletop[j])
  {
   current1.chromosome[j]=double(rand()%10000)/10000*(variabletop[j]-variablebottom[j])+variablebottom[j];
  }
  if (current1.chromosome[j]<variablebottom [j])
  {
   current1.chromosome[j]=double(rand()%10000)/10000*(variabletop[j]-variablebottom[j])+variablebottom[j];
  }
  }
  //回代
 }
 newpopulation.InsertAfter (newpopulation.Findindex(i),current);
 newpopulation.InsertAfter (newpopulation.Findindex(i),current1);
 }
 ASSERT(newpopulation.GetCount()==popsize);
 for (i=0;i<popsize;i++)
 {
 population.SetAt (population.Findindex(i),newpopulation.GetAt (newpopulation.Findindex(i)));
 }
 newpopulation.RemoveAll();
 index.RemoveAll();
}
void CMVSOGA:: findbestandworstindividual( ) 
{
 int i;
 bestindividual=population.GetAt(population.Findindex(best_index));
 worstindividual=population.GetAt(population.Findindex(worst_index));
 for (i=1;i<popsize; i++)
 {
 current=population.GetAt(population.Findindex(i));
 if (current.fitness>bestindividual.fitness)
 {
  bestindividual=current;
  best_index=i;
 }
 else if (current.fitness<worstindividual.fitness)
 {
  worstindividual=current;
  worst_index=i;
 }
 }
 population.SetAt(population.Findindex(worst_index),population.GetAt(population.Findindex(best_index)));
 //用最好的替代最差的。
 if (maxgeneration==0)
 {
 currentbest=bestindividual;
 }
 else
 {
 if(bestindividual.fitness>=currentbest.fitness)
 {
  currentbest=bestindividual;
 }
 }
}
void CMVSOGA:: calculatefitnessvalue() //适应度函数值计算,关键是适应度函数的设计
     //current变化,这段程序变化较大,特别是排序。
{
 int i;
 double temp;//alpha,beta;//适应度函数的尺度变化系数
 double cmax=100;
 for(i=0;i<popsize;i++)
 {
 current=population.GetAt(population.Findindex(i));
 if(current.value<cmax)
 {
  temp=cmax-current.value;
 }
 else
 {
  temp=0.0;
 }
 /*
 if((population[i].value+cmin)>0.0)
 {temp=cmin+population[i].value;}
 else
 {temp=0.0;
  }
 */
 current.fitness=temp;
 population.SetAt(population.Findindex(i),current); 
 }
}
void CMVSOGA:: performevolution() //演示评价结果,有冗余代码,current变化,程序应该改变较大
{
 if (bestindividual.fitness>currentbest.fitness)
 {
 currentbest=population.GetAt(population.Findindex(best_index));
 }
 else
 {
 population.SetAt(population.Findindex(worst_index),currentbest);
 }
}
void CMVSOGA::GetResult(double *Result)
{
 int i;
 for (i=0;i<variablenum;i++)
 {
 Result[i]=currentbest.chromosome[i];
 }
 Result[i]=currentbest.value;
}
 
void CMVSOGA::GetPopData(CList <double,double>&PopData) 
{
 PopData.RemoveAll();
 int i,j;
 for (i=0;i<popsize;i++)
 {
 current=population.GetAt(population.Findindex(i));
 for (j=0;j<variablenum;j++)
 {
  PopData.AddTail(current.chromosome[j]);
 }
 }
}
void CMVSOGA::SetfitnessData(CList <double,double>&PopData,double>&fitnessData,double>&ValueData)
{
 int i,j;
 for (i=0;i<popsize;i++)
 { 
 current=population.GetAt(population.Findindex(i)); //就因为这一句,出现了很大的问题。 
 for (j=0;j<variablenum;j++)
 {
  current.chromosome[j]=PopData.GetAt(PopData.Findindex(i*variablenum+j));
 }
 current.fitness=fitnessData.GetAt(fitnessData.Findindex(i));
 current.value=ValueData.GetAt(ValueData.Findindex(i));
 population.SetAt(population.Findindex(i),current);
 }
 fitnessData.RemoveAll();
 PopData.RemoveAll();
 ValueData.RemoveAll();
}
 
# re: C++遗传算法源程序
/********************************************************************
Filename: aiWorld.h
Purpose: 遗传算法,花朵演化。
Id:
copyright:
Licence:
*********************************************************************/
#ifndef AIWORLD_H_
#define AIWORLD_H_
 
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cmath>
 
#define kMaxFlowers 10
 
using std::cout;
using std::endl;
 
class ai_World
{
public:
ai_World()
{
srand(time(0));
}
~ai_World() {}
 
int temperature[kMaxFlowers]; //温度
int water[kMaxFlowers]; //水质
int sunlight[kMaxFlowers]; //阳光
int nutrient[kMaxFlowers]; //养分
int beneficialInsect[kMaxFlowers]; //益虫
int harmfulInsect[kMaxFlowers]; //害虫
 
int currentTemperature;
int currentWater;
int currentSunlight;
int currentNutrient;
int currentBeneficialInsect;
int currentHarmfulInsect;
 
/**
第一代花朵
*/
void Encode();
 
/**
花朵适合函数
*/
int fitness(int flower);
 
/**
花朵演化
*/
void Evolve();
 
/**
返回区间[start,end]的随机数
*/
inline int tb_Rnd(int start,int end)
{
if (start > end)
return 0;
else
{
//srand(time(0));
return (rand() % (end + 1) + start);
}
}
 
/**
显示数值
*/
void show();
};
// ----------------------------------------------------------------- //
void ai_World::Encode()
// ----------------------------------------------------------------- //
 
{
int i;
 
for (i=0;i<kMaxFlowers;i++)
{
temperature[i]=tb_Rnd(1,75);
water[i]=tb_Rnd(1,75);
sunlight[i]=tb_Rnd(1,75);
nutrient[i]=tb_Rnd(1,75);
beneficialInsect[i]=tb_Rnd(1,75);
harmfulInsect[i]=tb_Rnd(1,75);
}
 
currentTemperature=tb_Rnd(1,75);
currentWater=tb_Rnd(1,75);
currentSunlight=tb_Rnd(1,75);
currentNutrient=tb_Rnd(1,75);
currentBeneficialInsect=tb_Rnd(1,75);
currentHarmfulInsect=tb_Rnd(1,75);
 
currentTemperature=tb_Rnd(1,75);
 
}
// ----------------------------------------------------------------- //
int ai_World::fitness(int flower)
// ----------------------------------------------------------------- //
 
{
int thefitness;
 
 
thefitness=abs(temperature[flower]-currentTemperature);
thefitness=thefitness+abs(water[flower]-currentWater);
thefitness=thefitness+abs(sunlight[flower]-currentSunlight);
thefitness=thefitness+abs(nutrient[flower]-currentNutrient);
thefitness=thefitness+abs(beneficialInsect[flower]-currentBeneficialInsect);
thefitness=thefitness+abs(harmfulInsect[flower]-currentHarmfulInsect);
 
return (thefitness);
 
}
// ----------------------------------------------------------------- //
void ai_World::Evolve()
// ----------------------------------------------------------------- //
 
{
int fitTemperature[kMaxFlowers];
int fitWater[kMaxFlowers];
int fitSunlight[kMaxFlowers];
int fitNutrient[kMaxFlowers];
int fitBeneficialInsect[kMaxFlowers];
int fitHarmfulInsect[kMaxFlowers];
int fitness[kMaxFlowers];
int i;
int leastFit=0;
int leastFitIndex;
 
for (i=0;i<kMaxFlowers;i++)
if (fitness(i)>leastFit)
{
leastFit=fitness(i);
leastFitIndex=i;
}
 
temperature[leastFitIndex]=temperature[tb_Rnd(0,kMaxFlowers - 1)];
water[leastFitIndex]=water[tb_Rnd(0,kMaxFlowers - 1)];
sunlight[leastFitIndex]=sunlight[tb_Rnd(0,kMaxFlowers - 1)];
nutrient[leastFitIndex]=nutrient[tb_Rnd(0,kMaxFlowers - 1)];
beneficialInsect[leastFitIndex]=beneficialInsect[tb_Rnd(0,kMaxFlowers - 1)];
harmfulInsect[leastFitIndex]=harmfulInsect[tb_Rnd(0,kMaxFlowers - 1)];
 
for (i=0;i<kMaxFlowers;i++)
{
fitTemperature[i]=temperature[tb_Rnd(0,kMaxFlowers - 1)];
fitWater[i]=water[tb_Rnd(0,kMaxFlowers - 1)];
fitSunlight[i]=sunlight[tb_Rnd(0,kMaxFlowers - 1)];
fitNutrient[i]=nutrient[tb_Rnd(0,kMaxFlowers - 1)];
fitBeneficialInsect[i]=beneficialInsect[tb_Rnd(0,kMaxFlowers - 1)];
fitHarmfulInsect[i]=harmfulInsect[tb_Rnd(0,kMaxFlowers - 1)];
}
 
for (i=0;i<kMaxFlowers;i++)
{
temperature[i]=fitTemperature[i];
water[i]=fitWater[i];
sunlight[i]=fitSunlight[i];
nutrient[i]=fitNutrient[i];
beneficialInsect[i]=fitBeneficialInsect[i];
harmfulInsect[i]=fitHarmfulInsect[i];
}
 
for (i=0;i<kMaxFlowers;i++)
{
if (tb_Rnd(1,100)==1)
temperature[i]=tb_Rnd(1,75);
if (tb_Rnd(1,100)==1)
water[i]=tb_Rnd(1,100)==1)
sunlight[i]=tb_Rnd(1,100)==1)
nutrient[i]=tb_Rnd(1,100)==1)
beneficialInsect[i]=tb_Rnd(1,100)==1)
harmfulInsect[i]=tb_Rnd(1,75);
}
 
}
void ai_World::show()
{
// cout << "/t temperature water sunlight nutrient beneficialInsect harmfulInsect/n";
cout << "current/t " << currentTemperature << "/t " << currentWater << "/t ";
cout << currentSunlight << "/t " << currentNutrient << "/t ";
cout << currentBeneficialInsect << "/t " << currentHarmfulInsect << "/n";
for (int i=0;i<kMaxFlowers;i++)
{
cout << "Flower " << i << ": ";
cout << temperature[i] << "/t ";
cout << water[i] << "/t ";
cout << sunlight[i] << "/t ";
cout << nutrient[i] << "/t ";
cout << beneficialInsect[i] << "/t ";
cout << harmfulInsect[i] << "/t ";
cout << endl;
}
}
#endif // AIWORLD_H_
 
//test.cpp
#include <iostream>
#include "ai_World.h"
 
using namespace std;
 
int main()
{
ai_World a;
a.Encode();
// a.show();
for (int i = 0; i < 10; i++)
{
cout << "Generation " << i << endl;
a.Evolve();
a.show();
}
 
system("PAUSE");
return 0;
}

希望本文所述对大家的C++程序设计有所帮助。

关于在遗传算法中为多个“推销员” TSP实现交叉功能遗传算法中每个被选中的个体,一定会进行交叉操作的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于c# – 用于TSP的遗传算法中的Сrossover操作、c# – 遗传算法中的比赛评估、C++实现简单遗传算法、C++实现遗传算法等相关内容,可以在本站寻找。

本文标签: