示例#1
0
            public TIndividual Run(XFitnessFunction <TChromosome> fitnessFunction)
            {
                int generation = 0;

                var reproductionGroup = new List <TIndividual>();

                var currentPopulationsChromosomes = PopulationInitializer.Initialize();

                IReadOnlyList <TIndividual> currentPopulation = currentPopulationsChromosomes.Select(
                    chromosome => IndividualFactory.CreateIndividual(chromosome, fitnessFunction)
                    ).ToList();

                var bestSolution = currentPopulation[0];

                foreach (var individual in currentPopulation)
                {
                    if (individual.Fitness > bestSolution.Fitness)
                    {
                        bestSolution = individual;
                    }
                }

                while (ContinueCondition.ShouldContinue(currentPopulation, generation))
                {
                    var pairs = Breeding.Select(currentPopulation);

                    reproductionGroup.Clear();

                    foreach (var Compound in pairs.Select(pair => Crossover.Crossover(pair)))
                    {
                        reproductionGroup.AddRange(
                            Compound
                            .Select(chromosome => Mutation.Mutate(chromosome))
                            .Select(mutant => IndividualFactory.CreateIndividual(mutant, fitnessFunction)));
                    }

                    foreach (var individual in reproductionGroup)
                    {
                        if (individual.Fitness > bestSolution.Fitness)
                        {
                            bestSolution = individual;
                        }
                    }

                    currentPopulation = Strategy.NextGeneration(
                        currentPopulation,
                        reproductionGroup
                        );

                    generation++;
                }

                return(bestSolution);
            }