Пример #1
0
    public MyDNA <T> Crossover(MyDNA <T> otherParent)
    {
        MyDNA <T> child = new MyDNA <T>(Genes.Length, random, getRandomGene, fitnessFunction, shouldInitGenes: false);

        for (int i = 0; i < Genes.Length; i++)
        {
            child.Genes[i] = random.NextDouble() < 0.5 ? Genes[i] : otherParent.Genes[i];
        }

        return(child);
    }
Пример #2
0
 public int CompareDNA(MyDNA <T> a, MyDNA <T> b)
 {
     if (a.Fitness > b.Fitness)
     {
         return(-1);
     }
     else if (a.Fitness < b.Fitness)
     {
         return(1);
     }
     else
     {
         return(0);
     }
 }
Пример #3
0
    public void CalculateFitness()
    {
        fitnessSum = 0;
        MyDNA <T> best = Population[0];

        for (int i = 0; i < Population.Count; i++)
        {
            fitnessSum += Population[i].CalculateFitness(i);

            if (Population[i].Fitness > best.Fitness)
            {
                best = Population[i];
            }
        }

        BestFitness = best.Fitness;
        best.Genes.CopyTo(BestGenes, 0);
    }
Пример #4
0
    public void NewGeneration()
    {
        if (Population.Count <= 0)
        {
            return;
        }

        CalculateFitness();
        Population.Sort(CompareDNA);

        newPopulation.Clear();

        for (int i = 0; i < Population.Count; i++)
        {
            if (i < Elitism)
            {
                newPopulation.Add(Population[i]);
            }
            else
            {
                MyDNA <T> parent1 = ChooseParent();
                MyDNA <T> parent2 = ChooseParent();

                MyDNA <T> child = parent1.Crossover(parent2);

                child.Mutate(MutationRate);

                newPopulation.Add(child);
            }
        }

        List <MyDNA <T> > tempList = Population;

        Population    = newPopulation;
        newPopulation = tempList;

        Generation++;
    }