⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 yichuan.txt

📁 遗传算法的一个代码
💻 TXT
📖 第 1 页 / 共 3 页
字号:
  iflg[pop_size-1]=1;
  /* 子个体画面表示 */
  world[x3][y3]=gene[pop_size-1][0]+1;
  g_disp_unit(x3,y3,gene[pop_size-1][0]+1);
  }
  }
  }
  void act_individual(n) /* 为行动范围内的其他生物和食物决定行动 */
  int n;
  {
  int i,j,k,pattern,action,cr,ca;
  int act[3]; /* act[0]:攻击 act[1]:获取食物 act[2]:交配 */
  int pat[6][3]={{1,2,3},{1,3,2},{2,1,3},
  {3,1,2},{2,3,1},{3,2,1}};
  /* pat:行动优先顺序 {攻击,获取食物,交配} */
  int sp;
  double rnd;
  sp=decode_gene(n,0,1)+1;
  for(i=0;i<3;i++) act [ i]=0;
  for(i=-1;i<=1;i++)
  for(j=-1;j<=1;j++)
  {
  if(i!=0||j!=0)
  {
  k=get_world(iatr[n][0]+j,iatr[n][1]+i);
  if(k==1||k==2) act[0]=1;
  if(k==3||k==5) act[1]=1;
  if(k==sp) act[2]=1;
  }
  }
  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;i<food_size;i++) fflg [ i]=1;
  }
  void act_lives() /* 改变状态(移动或行动) */
  {
  int i,j,k,x,y,move,a;
  for(i=0;i{
  if(iflg [ i]==1)
  {
  move=1;
  for(j=-1;j<=1;j++)
  for(k=-1;k<=1;k++)
  {
  if(j!=0||k!=0)
  {
  a=get_world(iatr [ i][0]+k,iatr [ i][1]+j);
  if(a==1||a==2||a==3||a==5)
  move=0;
  }
  }
  if(move==1)
  move_individual(i);
  else
  act_individual(i);
  }
  }
  }
  void increase_age() /* 个体年龄增1 */
  {
  int i,j,s;
  for(i=0;i{
  if(iflg [ i]==1)
  {
  j=decode_gene(i,1,4);
  s=SL_MIN+j;
  iatr [ i][3]++;
  if(iatr [ i][3]>s)
  remove_life(i);
  }
  }
  }
  void increase_frsh() /* 食物新鲜度增1 */
  {
  int i;
  for(i=0;i<food_size;i++)
  if(fflg [ i]==1)
  {
  fatr [ i][3]++;
  if((fatr [ i][2]==0 && fatr [ i][3]>TL1)||
  (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;i<food_size;i++)
  if(fflg [ i]==1)
  {
  new_food++;
  for(j=0;j<4;j++)
  fatr[new_food-1][j]=fatr [ i][j];
  }
  food_size=new_food;
  /* 检查个体 */
  new_pop=0;
  for(i=0;iif(iflg [ i]==1)
  {
  new_pop++;
  /* 遗传基因复制 */
  for(j=0;j<G_LENGTH;j++)
  gene[new_pop-1][j]=gene [ i][j];
  /* 属性复制 */
  for(j=0;j<4;j++)
  iatr[new_pop-1][j]=iatr [ i][j];
  }
  pop_size=new_pop;
  }
  void make_foods() /* 产生一代中植物性食物 */
  {
  int i,x,y;
  for(i=0;i<NEWFOODS;i++)
  {
  if(food_size+1<=MAX_FOOD)
  {
  food_size++;
  find_empty(&x,&y);
  fatr[food_size-1][0]=x;
  fatr[food_size-1][1]=y;
  fatr[food_size-1][2]=0; /* 植物性 */
  fatr[food_size-1][3]=0;
  fflg[food_size-1]=1;
  world[x][y]=3;
  g_disp_unit(x,y,3);
  }
  }
  }
  void calc_population(n1,n2) /* 计算生物1和2 的个体数 */
  int *n1,*n2;
  {
  int i,p1,p2;
  p1=0;p2=0;
  if(pop_size>0)
  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 <code>serialVersionUID</code>
  */
  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;
  }
  }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -