Example #1
0
void GA_BuildTower::Init(const vector<Vec2>& cand_grid, 
			 const vector<int>& level,
			 const vector<int>& type)

{
  populations.clear();
  GenoType species;
  for (int i = 0; i < pop_size; ++i) {
    species.fitness = 0;
    species.rfitness = 0;
    species.cfitness = 0;
    species.gene.clear();
    for (int j = 0; j < gene_cnt; ++j) species.gene.push_back(Tower(level[j], type[j], 
								    cand_grid[j].x, cand_grid[j].y));
    populations.push_back(species);
  }

  CalFitness();

  double best_fitness = 0;
  for (int i = 0; i < pop_size; ++i) 
    if (populations[i].fitness > best_fitness) {
      best_fitness = populations[i].fitness;
      best = populations[i];
    }
}
Example #2
0
void GA_BuildTower::Run()
{
  for (int i = 0; i < generation_cnt; ++i) {
    Select();
    Crossover();
    Mutate();
    CalFitness();
    Elitist();
  }
}
Example #3
0
// 进化
void CGA::Evolution()
{
    int nCount = 0;
     
    while ( ++nCount <= m_nMaxGenerations )
    {  
        Select();
        Cross();
        Mut();

		int nIndex = -1;
        // 计算该代的适应度,找出此种群中最优的解 
        int nMinFitness = CalFitness(nIndex);
        int nCurGeneration = IncreaseGeneration(); 

        if ( nMinFitness < m_nBestFitness )
        {
            m_nBestFitness = nMinFitness;
            m_nBestGeneration = nCurGeneration;
        }

		// 记录当前种群、最小适应度、以及最小适应度是哪个染色体 
		Generations curGeneration;
		curGeneration.group = m_vecChromosomes;
		curGeneration.nCurFitness = nMinFitness;
		curGeneration.nCurMinIndex = nIndex;
		m_vecAllGenerations.push_back(curGeneration);
		
		if ( nIndex >= 0 )
		{ 
			Draw(m_vecChromosomes[ nIndex ]); 
			Sleep(1000 * 2);
		} 

         
    } 

	// 找到所有代中 适应度最小 所在的代 最小的个体
	if ( m_nBestGeneration >= 1 )
	{
		int nIndex = m_vecAllGenerations[ m_nBestGeneration - 1].nCurMinIndex;
		Draw( m_vecAllGenerations[ m_nBestGeneration - 1 ].group[ nIndex ]); 

		// 图中所有弧

	} 

	Finish();
}