Пример #1
0
        private void Selection()
        {
            ElitePopulation = Population.OrderBy(ch => ch.Fitness).Take((int)(SizeOfPopulation * ElitRate)).ToList();
            if (BestChromosome.Fitness >= ElitePopulation.ElementAt(0).Fitness)
            {
                BestChromosome.Fitness = ElitePopulation.ElementAt(0).Fitness;
                BestChromosome.Genes   = ElitePopulation.ElementAt(0).Genes;
            }

            Population[0] = ElitePopulation[0];
        }
Пример #2
0
        private void Crossover()
        {
            Random random = new Random();

            for (int i = 1; i < SizeOfPopulation; i++)
            {
                Chromosome father = ElitePopulation.ElementAt(random.Next(ElitePopulation.Count));
                Chromosome mother = ElitePopulation.ElementAt(random.Next(ElitePopulation.Count));

                Chromosome kid = Mate(father, mother);
                kid.Fitness   = _baseRoute.TotalDistance(kid);
                Population[i] = kid;
            }

            Chromosome Mate(Chromosome father, Chromosome mother)
            {
                Chromosome offspring = new Chromosome(father.Genes.Length);

                for (int i = 0; i < father.Genes.Length; i++)
                {
                    if (i % 2 == 0)
                    {
                        offspring.Genes[i] = father.Genes.ElementAt(i);
                    }
                }
                for (int i = 0; i < mother.Genes.Length; i++)
                {
                    if (!offspring.Genes.Contains(mother.Genes[i]))
                    {
                        int index = offspring.Genes.ToList().IndexOf(-1);
                        offspring.Genes[index] = mother.Genes[i];
                    }
                }

                return(offspring);
            }
        }