コード例 #1
0
ファイル: Program.cs プロジェクト: szymekc/KnapsackProblem
        static double[] RunGeneticAlgorithm(Task task, int pop_size, int iterations, int tournament_size, double crossover_rate, double mutation_rate)
        {
            Population population = new Population(task.n, pop_size);
            var        bestScores = new double[iterations];

            for (int i = 0; i < iterations; i++)
            {
                population.Evaluate(task);
                Population new_population = new Population(pop_size);
                for (int j = 0; j < pop_size; j++)
                {
                    Individual parent1 = population.Tournament(tournament_size, task);
                    Individual parent2 = population.Tournament(tournament_size, task);
                    Individual child   = parent1.Crossover(parent2, crossover_rate);
                    child.Mutate(mutation_rate);
                    new_population.individuals[j] = child;
                }
                population = new_population;
                List <int> scores = new List <int>();
                foreach (Individual el in population.individuals)
                {
                    scores.Add(el.score);
                }
                bestScores[i] = (double)scores.Max();
            }
            return(bestScores);
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: szymekc/KnapsackProblem
        static int RunGeneticForComparison(Task task, int pop_size, int iterations, int tournament_size, double crossover_rate, double mutation_rate)
        {
            geneticTime.Start();
            Population population = new Population(task.n, pop_size);
            var        bestScores = new double[iterations];

            for (int i = 0; i < iterations; i++)
            {
                population.Evaluate(task);
                Population new_population = new Population(pop_size);
                for (int j = 0; j < pop_size; j++)
                {
                    Individual parent1 = population.Tournament(tournament_size, task);
                    Individual parent2 = population.Tournament(tournament_size, task);
                    Individual child   = parent1.Crossover(parent2, crossover_rate);
                    child.Mutate(mutation_rate);
                    new_population.individuals[j] = child;
                }
                population = new_population;
            }
            geneticTime.Stop();
            ts = geneticTime.Elapsed;
            return(population.individuals.Max((a) => a.score));
        }