展会信息港展会大全

求遗传算法(GA)C语言代码
来源:互联网   发布日期:2011-09-27 11:35:10   浏览:11630次  

导读:.----来个例子,大家好理解..-- 基于遗传算法的人工生命模拟 #includestdio.h #includestdlib.h #includegraphics.h #includemath.h #includetime.h #includest...

其他答案

  unsigned char fflg[MAX_FOOD]; /* 食物有无状态标志变量 */  unsigned char world[MAX_WX][MAX_WY]; /* 虚拟环境的数据 */  unsigned char /* 各中行为模式数据 */  life1[5][5]={{0,0,1,0,0},{0,1,0,1,0},{1,0,0,0,1},{0,1,0,1,0},{0,0,1,0,0}};  unsigned char  life2[5][5]={{1,1,1,1,1},{1,0,0,0,1},{1,0,0,0,1},{1,0,0,0,1},{1,1,1,1,1}};  unsigned char  food1[5][5]={{0,0,0,1,0},{0,0,1,1,0},{0,1,0,1,0},{0,0,1,1,0},{0,0,0,1,0}};  unsigned char  food2[5][5]={{0,0,0,1,0},{0,0,1,1,0},{0,1,1,1,0},{0,0,1,1,0},{0,0,0,1,0}};  int pop_size; /* 个体总数 */  int iatr[MAX_POP][4]; /* 个体属性 */  /* iatr[][0] 个体当前位置x坐标 */  /* iatr[][1] 个体当前位置y坐标 */  /* iatr[][2] 内部能量 */  /* iatr[][3] 年龄属性 */  int food_size; /* 食物总数 */  int fatr[MAX_FOOD][4]; /* 食物属性 */  /* fatr[][0] 食物当前位置x坐标 */  /* fatr[][1] 食物当前位置y坐标 */  /* fatr[][2]=0 : 植物性 =1:动物性 */  /* fatr[][3] 新鲜程度 */  int wx,wy; /* 虚拟环境的长宽度 */  void uni_crossover(gene,g1,g2,g3,ratio1,g_length) /* 均匀交叉 */  unsigned char *gene; /* 遗传基因 */  int g1,g2,g3; /* g1 g2 父个体编号 g3 子个体编号 */  double ratio1; /* 父个体g1被选中的概率 */  int g_length; /* 个体遗传基因的位长 */  {  unsigned char *gene1; /* 父1遗传基因的指针 */  unsigned char *gene2; /* 父2遗传基因的指针 */  unsigned char *gene3; /* 子遗传基因的指针 */  double rnd,r1;  int i;  gene1=gene+g_length*g1;  gene2=gene+g_length*g2;  gene3=gene+g_length*g3;  r1=(int)(10000.0*ratio1);  for(i=0;i

您已经评价过!

您已经评价过!

  }  void g_draw_world() /* 显示虚拟环境画面 */  {  int i,j;  for(i=0;i=n1) g [ i]=0; else g [ i]=1;  }

您已经评价过!

您已经评价过!

  x=220;  for(i=0;i<12;i++)  {  y=202+i*16;  for(j=bits [ i][0];j<=bits [ i][1];j++)  if(g[j]==0)  g_text(x+(j-bits [ i][0])*16,y,4,"0");  else  g_text(x+(j-bits [ i][0])*16,y,4,"1");  }  }  }  void g_disp_char(x,y,x1,y1,x2,y2,v)   int x,y,x1,y1,x2,y2;  unsigned char v;  {  char c[10];  if(x>=x1&& x<=x2-8 && y>=y1 && y<=y2-10)  {  switch(v)  {  case 0: strcpy(c,"0");break;  case 1: strcpy(c,"+");break;  case 2: strcpy(c,"-");break;  case 3: strcpy(c,"x");  }  g_text(x,y,15,c);  }  }  void remove_life(n) /* 消除第n个个体 */  int n;  {  iflg[n]=0;  world[iatr[n][0]][iatr[n][1]]=0;  g_disp_unit(iatr[n][0],iatr[n][1],0);  if(food_size+1<=MAX_FOOD)  {  food_size++;  fatr[food_size-1][0]=iatr[n][0];  fatr[food_size-1][1]=iatr[n][1];  fatr[food_size-1][2]=1;  fatr[food_size-1][3]=0;  fflg[food_size-1]=1;  world[iatr[n][0]][iatr[n][1]]=5;  g_disp_unit(iatr[n][0],iatr[n][1],5);  }  }  void remove_food(n) /* 消除第n个食物 */  int n;  {  fflg[n]=0;  world[fatr[n][0]][fatr[n][1]]=0;  g_disp_unit(fatr[n][0],fatr[n][1],0);  }  void make_lives_and_foods() /* 设置虚拟环境中生物与食物 */  {  int x,y,i,j;  pop_size=0;  food_size=0;  for(y=0;yMAX_WX)  {  setcolor(15);  disp_hz16("虚拟环境长度(10-60)",10,210,20);  gscanf(300,210,4,0,3,"%s",choice);  wx=atoi(choice);  }  wy=0;  while(wy<10||wy>MAX_WY)  {  setcolor(15);  disp_hz16("虚拟环境宽度(10-32)",10,240,20);  gscanf(300,240,4,0,3,"%s",choice);  wy=atoi(choice);  }  for(i=0;iMAX_POP) num=MAX_POP;  for(i=0;iMAX_FOOD) num=MAX_FOOD;  for(i=0;i=6) world[x][y]=4;  }  /* 设定生物 */  num=(int)(size*R_LIFE);  for(i=0;i

您已经评价过!

您已经评价过!

  }  }  int get_world(x,y) /*坐标(x,y)处环境值 */  int x,y;  {  if(x>=0 && x=0 && y=0 && x2=0 && y2cos_max)  {  cos_max=_cos;j=i;  }  }  dx=cx+(int)vect[j][0];  dy=cy+(int)vect[j][1];  if(dx>=0 && dx=0 && dy

您已经评价过!

您已经评价过!

 /* 计算双方的 Attack量 */  sa1=(double)decode_gene(n,19,3);  da1=(double)decode_gene(n,22,3);  sa2=(double)decode_gene(n2,19,3);  da2=(double)decode_gene(n2,22,3);  rnd1=(double)random(1001)/1000.0;  rnd2=(double)random(1001)/1000.0;  attack1=(double)iatr[n][2]+sa1*20.0/7.0*rnd1+da1*20.0/7.0*rnd2;  rnd1=(double)random(1001)/1000.0;  rnd2=(double)random(1001)/1000.0;  attack2=(double)iatr[n2][2]+sa2*20.0/7.0*rnd1+da2*20.0/7.0*rnd2;  /* 减少内部能量 */  La1=decode_gene(n,25,3);  La2=decode_gene(n2,25,3);  rnd1=(double)random(1001)/1000.0;  iatr[n][2]=iatr[n][2]-(int)((double)La1*rnd1);  rnd2=(double)random(1001)/1000.0;  iatr[n2][2]=iatr[n2][2]-(int)((double)La2*rnd2);  if(attack1>=attack2) /* 胜者: n 败者:n2 */  iatr[n2][2]=iatr[n2][2]-40;  else /* 胜者: n2 败者:n */  iatr[n][2]=iatr[n][2]-40;  if(iatr[n][2]<=0) remove_life(n);  if(iatr[n2][2]<=0) remove_life(n2);  }  void act2_eat(n) /* 个体n获取行动范围内的食物 */  int n;  {  int sft[8][2]={{1,0},{1,1},{0,1},{-1,1},  {-1,0},{-1,-1},{0,-1},{1,-1}};  int x1,y1,x2,y2,n2,ef;  int found,rndnum;  x1=iatr[n][0];y1=iatr[n][1];  /* 获取食物位置(x2,y2) */  found=0;  while(found==0)  {  rndnum=random(8);  x2=x1+sft[rndnum][0];  y2=y1+sft[rndnum][1];  if(get_world(x2,y2)==3||get_world(x2,y2)==5)  found=1;  }  /* 增加内部能量 */  ef=decode_gene(n,28,4); /* 食物吸取效率 */  iatr[n][2]=iatr[n][2]+(int)(40.0*(50.0+(double)ef*50.0/15.0)/100.0);  if(iatr[n][2]>100) iatr[n][2]=100;  /* 检查食物号n2 */  found=0;n2=0;  while(found==0)  {  if(fatr[n2][0]==x2 && fatr[n2][1]==y2 && fflg[n2]==1)  found=1; else n2++;  }  remove_food(n2);  }  void act3_makechild(n) /* 个体n与行动范围内的其他生物个体交配产生子个体 */  int n;  {  int i,j,k,x,y,x2,y2,found,n2,trial;  int x3,y3;  double rnd;  if(pop_size+1<=MAX_POP)  {  x=iatr[n][0];y=iatr[n][1];  found=0;  while(found==0)  {  x2=x+random(3)-1;  y2=y+random(3)-1;  if(x2!=x||y2!=y)  if(get_world(x2,y2)==gene[n][0]+1);  found=1;  }  /* 检查交配对象个体号n2 */  found=0; n2=0;  while(found==0)  {  if((iatr[n2][0]==x2 || iatr[n2][1]==y2) && iflg[n2]==1)  found=1; else n2++;  if(n2>=pop_size-1) return;  }  /* 确定产生个体位置 */  found=0;trial=0;  while(found==0 && trial<50)  {  i=random(3)-1;j=random(3)-1;  k=random(2);  if(k==0) { x3=x+i;y3=y+j;}  else { x3=x2+i;y3=y2+j;}  if(get_world(x3,y3)==0) found=1;  trial++;  }  if(found==1)  {  /* 个体 n与个体 n2产生子个体 */  pop_size++;  /* 均匀交叉 */  uni_crossover(gene,n,n2,pop_size-1,0.5,G_LENGTH);  /* 变异 */  for(i=1;i

您已经评价过!

您已经评价过!

  cr=decode_gene(n,16,3);  rnd=(double)random(10001)/10000.0;  if(rnd<=(double)cr/7.0)  {  action=random(3);  while(act[action]==0)  action=random(3);  }  else  {  ca=decode_gene(n,13,3); /* ca行动特点 */  if(ca<3) pattern=0;else pattern=ca-2;  /* 基本行动模式pattern 0-5 */  i=0;  action=pat[pattern] [ i]-1;  while( act[action]==0)  {  i++;  action=pat[pattern] [ i]-1;  }  }  switch(action+1)  {  case 1: act1_attack(n);break;  case 2: act2_eat(n);break;  case 3: act3_makechild(n);  }  }  void init_flags() /* 状态标志初始化 */  {  int i;  for(i=0;ifor(i=0;is)  remove_life(i);  }  }  }  void increase_frsh() /* 食物新鲜度增1 */  {  int i;  for(i=0;iTL1)||  (fatr [ i][2]==1 && fatr [ i][3]>TL2))  remove_food(i);  }  }  void gabage_col() /* 死去个体及消减食物清除*/  {  int i,j;  int new_pop,new_food;  /* 检查食物 */  new_food=0;  for(i=0;i0)  for(i=0;iif(gene [ i][0]==0) p1++; else p2++;  *n1=p1;  *n2=p2;  }  main() /* 主程序 */  {  int i,work;  int n1,n2,n1old,n2old;  char choice[2];  randomize();  /* 图形界面初始化 */  g_init();  settextstyle(0,0,4);  gprintf(220,20,4,0,"ALIFE");  setcolor(9);  disp_hz24("基于遗传算法的人工生命模拟",150,60,25);  setcolor(15);  disp_hz16("人工环境及生物分布",10,160,20);  disp_hz16("1:随机产生 2: 读文件产生 ==>",10,190,20);  gscanf(300,190,15,1,4,"%s",choice);  work=atoi(choice);  if(work==2) load_world_file();else make_world();  make_lives_and_foods();  /*状态初始化 */  init_flags();  /*计算个体数 */  calc_population(&n1old,&n2old);  /*生成初始画面*/  g_init_frames();  /*虚拟世界画面*/  g_draw_world();  /* 显示初始图形 */  g_init_graph();  for(i=1;i<121;i++)  {  /*状态初始化 */  init_flags();  /* 改变状态(移动或行动) */  act_lives();  /* 个体年龄增加 */  increase_age();  /* 食物新鲜度增加 */  increase_frsh();  /*死去个体及消减食物清除*/  gabage_col();  /*产生新的食物 */  make_foods();  /* 求生物1和2 的个体数 */  calc_population(&n1,&n2);  /* 个体数变化的图形更新 */  g_plot_population(i,n1,n2,n1old,n2old);  n1old=n1;n2old=n2;  /* 显示最佳遗传基因 */  g_disp_genotype();  }  setcolor(9);  disp_hz16("回车键结束",10,430,20);  getch();  }

您已经评价过!

您已经评价过!

  java jgap实例  package demo;  import java.io.File;  import java.io.FileNotFoundException;  import org.jgap.Chromosome;  import org.jgap.Configuration;  import org.jgap.FitnessFunction;  import org.jgap.Gene;  import org.jgap.Genotype;  import org.jgap.IChromosome;  import org.jgap.UnsupportedRepresentationException;  import org.jgap.data.DataTreeBuilder;  import org.jgap.data.IDataCreators;  import org.jgap.impl.DefaultConfiguration;  import org.jgap.impl.IntegerGene;  import org.jgap.xml.XMLDocumentBuilder;  import org.jgap.xml.XMLManager;  import org.w3c.dom.Document;  import examples.MinimizingMakeChangeFitnessFunction;  /**  * Copyright: youhow.net (c) 2005-2008  * Company: youhow.net  *  * 遗传算法DEMO  * 从文件读取数字进行排序  *  * @version 1.0 (2008-6-12 neo(starneo@gmail.com))  */  public class GaDemo  {  /**  * @param args  */  public static void main(String[] args) throws Exception  {  //构型  Configuration conf = new DefaultConfiguration();  // Care that the fittest individual of the current population is  // always taken to the next generation.  // Consider: With that, the pop. size may exceed its original  // size by one sometimes!  // ....-  conf.setPreservFittestIndividual(true);  // Set the fitness function we want to use, which is our  // MinimizingMakeChangeFitnessFunction. We construct it with  // the target amount of change passed in to this method.  // ...--  FitnessFunction myFunc = new GaDemoFitnessFunction();  conf.setFitnessFunction(myFunc);  Gene[] sampleGenes = new Gene[2];  sampleGenes[0] = new IntegerGene(conf,0,9999999);  sampleGenes[1] = new IntegerGene(conf,0,9999999);  IChromosome sampleChromosome = new Chromosome(conf, sampleGenes);  conf.setSampleChromosome(sampleChromosome);  conf.setPopulationSize(80);  Genotype population;  try  {  Document doc = XMLManager.readFile(new File("GADEMO.xml"));  population = XMLManager.getGenotypeFromDocument(conf, doc);  }  catch (UnsupportedRepresentationException uex)  {  // JGAP codebase might have changed between two consecutive runs.  // ....--  population = Genotype.randomInitialGenotype(conf);  }  catch (FileNotFoundException fex)  {  population = Genotype.randomInitialGenotype(conf);  }  // Evolve the population. Since we don't know what the best answer  // is going to be, we just evolve the max number of times.  // ....---  long startTime = System.currentTimeMillis();  for (int i = 0; i < 50; i++)  {  population.evolve();  }  long endTime = System.currentTimeMillis();  System.out.println("Total evolution time: " + (endTime - startTime) + " ms");  IChromosome bestSolutionSoFar = population.getFittestChromosome();  System.out.println("\t" + MinimizingMakeChangeFitnessFunction.getNumberOfCoinsAtGene(bestSolutionSoFar, 0));  System.out.println("\t" + MinimizingMakeChangeFitnessFunction.getNumberOfCoinsAtGene(bestSolutionSoFar, 1));  DataTreeBuilder builder = DataTreeBuilder.getInstance();  IDataCreators doc2 = builder.representGenotypeAsDocument(population);  // create XML document from generated tree  XMLDocumentBuilder docbuilder = new XMLDocumentBuilder();  Document xmlDoc = (Document) docbuilder.buildDocument(doc2);  XMLManager.writeFile(xmlDoc, new File("GADEMO.xml"));  }  }

您已经评价过!

您已经评价过!

  package demo;  import org.jgap.FitnessFunction;  import org.jgap.IChromosome;  /**  * Copyright: youhow.net (c) 2005-2008  * Company: youhow.net  *  * GaDemoFitnessFunction class说明  *  * @version 1.0 (2008-6-12 neo(starneo@gmail.com))  */  public class GaDemoFitnessFunction extends FitnessFunction  {  /**  * Comment for serialVersionUID  */  private static final long serialVersionUID = 1L;  /**  * @see org.jgap.FitnessFunction#evaluate(org.jgap.IChromosome)  */  @Override  protected double evaluate(IChromosome a_subject)  {  int totalCoins = 1;  int numberOfGenes = a_subject.size();  for (int i = 0; i < numberOfGenes; i++)  {  totalCoins += (Integer) a_subject.getGene(i).getAllele();  }  return totalCoins;  }  }/*全部完成*/

您已经评价过!

您已经评价过!


赞助本站

AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港