public static List <Genome> GenerateGenomes(int m_populationSize, Population pPreviousPopulation) { List <Genome> m_nextGeneration = new List <Genome>(); for (int i = 0; i < m_populationSize; i += 2) { int pidx1 = RouletteSelection(pPreviousPopulation); int pidx2 = RouletteSelection(pPreviousPopulation); Genome parent1; Genome parent2; Genome child1; Genome child2; parent1 = pPreviousPopulation[pidx1]; parent2 = pPreviousPopulation[pidx2]; if (GA.mRandom.NextDouble() < CrossoverRate) { GA.Crossover(parent1, parent2, out child1, out child2); } else { child1 = new Genome(parent1); child2 = new Genome(parent2); } Mutator(child1); Mutator(child2); m_nextGeneration.Add(new Genome(child1)); m_nextGeneration.Add(new Genome(child2)); } return(m_nextGeneration); }
public static void Mutator(Genome pGenome) { for (int pos = 0; pos < Genome.mLength; pos++) { if (GA.mRandom.NextDouble() < MutationRate) { pGenome[pos] = GA.GetRandomGene(); } } }
public static void Main(string[] args) { List <Population> mPopulations = new List <Population>(); GA.CrossoverRate = 0.5; GA.MutationRate = 0.1; Genome.mLength = 10; int m_populationSize = 10; double m_selectionRate = 0.8; //80% kills in population int m_generationSize = 2000; Population pop = new Population(0, GA.GenerateInitialGenomes(m_populationSize)); pop.DoMagic(m_selectionRate); pop.Info(); mPopulations.Add(pop); for (int i = 0; i < m_generationSize; i++) { Population pop2 = new Population(i, GA.GenerateGenomes(m_populationSize, mPopulations[i])); pop2.DoMagic(m_selectionRate); pop2.Info(); mPopulations.Add(pop2); if (pop2.mMaxFitness > 9.8) { break; } } mPopulations.Sort(delegate(Population x, Population y) { if (x.GetFitness() > y.GetFitness()) { return(1); } else if (x.GetFitness() == y.GetFitness()) { return(0); } else { return(-1); } }); mPopulations[mPopulations.Count - 1].Output(); }