Ejemplo n.º 1
0
        // 选择用于交叉的个体,确保最差的个体不会进来
        private static GiftTicketIndividual TournamentSelection(GiftTicketPopulation pop)
        {
            GiftTicketPopulation tournament = new GiftTicketPopulation(tournamentSize, false);

            for (int i = 0; i < tournamentSize; i++)
            {
                int randomId = (int)(new Random().NextDouble() * pop.Size());
                tournament.SaveIndividual(i, pop.GetIndividual(randomId));
            }
            GiftTicketIndividual fittest = tournament.GetFittest();

            return(fittest);
        }
Ejemplo n.º 2
0
        // 进化一个种群
        public static GiftTicketPopulation EvolvePopulation(GiftTicketPopulation pop)
        {
            GiftTicketPopulation newPopulation = new GiftTicketPopulation(pop.Size(), false);

            // 保留最优秀的个体
            if (elitism)
            {
                newPopulation.SaveIndividual(0, pop.GetFittest());
            }
            // 交叉种群
            int elitismOffset;

            if (elitism)
            {
                elitismOffset = 1;
            }
            else
            {
                elitismOffset = 0;
            }
            // 交叉产生新的个体
            for (int i = elitismOffset; i < pop.Size(); i++)
            {
                //    Console.WriteLine("交叉产生新个体");
                //确保不要把最差的个体选进来
                GiftTicketIndividual indiv1   = TournamentSelection(pop);
                GiftTicketIndividual indiv2   = TournamentSelection(pop);
                GiftTicketIndividual newIndiv = Crossover(indiv1, indiv2);
                newPopulation.SaveIndividual(i, newIndiv);
            }

            // 变异
            for (int i = elitismOffset; i < newPopulation.Size(); i++)
            {
                Mutate(newPopulation.GetIndividual(i));
            }

            return(newPopulation);
        }