Listing 5 More member functions of class CGAPopulation
#include <stdlib.h> #include <stdio.h> #include <float.h> #include <assert.h> #include <string.h> #include "pop.h" #include "random. h" // Constructor. It creates a population of chromosomes // where the probability that each bit is true // increases with each creation, then it creates a // complement of each of the created chromosomes. CGAPopulation::CGAPopulation( unsigned int Size, unsigned int Length, float MaxMutationRate) { assert(Size && Length); m_MaxSize = Size; m_CurrentSize = 0; m_Generation = 0; m_MaxMutationRate = MaxMutationRate; m_Data = new CGAChromosome*[m_MaxSize]; CGAChromosome::InitializeChromosomeClass(Length); for (unsigned int idx = 1; idx <= m_MaxSize / 2; idx++) { CGAChromosome* Temp = new CGAChromosome(idx / (float)m_MaxSize); CGAChromosome* CompTemp = Temp->complement(); Merge(Temp); Merge(CompTemp); } } // Default destructor CGAPopulation::~CGAPopulation() { for (unsigned int idx = 0; idx < m_MaxSize; idx++) { delete m_Data[idx]; } delete m_Data; } // Merge sort the new chromosome, assume that there no // holes in the array. void CGAPopulation::Merge( CGAChromosome* NewChromosome) { assert(m_CurrentSize < m_MaxSize); for (unsigned int idx = 0; idx < m_CurrentSize; id++) { if (NewChromosome->GetFitness() > m_Data[idx]->GetFitness()) { break; } } memmove(&m_Data[idx + 1], &m_Data[idx], sizeof(m_Data) * (m_CurrentSize - idx)); m_Data[idx] = NewChromosome; m_CurrentSize++; } // These functions randomly select a chromosome from // the ranked array, where the probability of selection // is related to the individual's position in the // array. ReplaceChromosome calculates an individual's // probability for replacement by Rank(X) / Total. // GetParent calculates an individual's probability for // parenthood by (Total - Rank(X)) / Total). CGAChromosome* CGAPopulation::GetParent() { float Selection; do { Selection = Rand0UpTo1(); } while (Flip(Selection)); return m_Data[(int)(Selection * m_MaxSize)]; } // Replace a poor chromosome with the new one. void CGAPopulation::ReplaceChromosome( CGAChromosome* NewChromosome) { float Selection; do { Selection = Rand0UpTo1(); } while (Flip(Selection)); unsigned int idx = m_MaxSize - (int)(Selection * m_MaxSize) - 1; delete m_Data[idx]; memmove(&m_Data[idx], &m_Data[idx + 1], sizeof(m_Data) * (m_CurrentSize - idx - 1)); m_CurrentSize--; Merge(NewChromosome); } // Create two offspring and replace two members of the // chromosome array. void CGAPopulation::CreateNextGeneration(void) { CGAChromosome *Parent1, *Parent2, *Child1, *Child2; Parent1 = GetParent(); Parent2 = GetParent(); Crossover(Parent1, Parent2, Child1, Child2, CalcSimilarityRatio(Parentl, Parent2) * m_MaxMutationRate); ReplaceChromosome(Child1); ReplaceChromosome(Child2); m_Generation++; } /* End of File */