コード例 #1
0
 // Create a new generation
 public void generate()
 {
     // Refill the population with children from the mating pool
     for (int i = 0; i < population.Length; i++)
     {
         int     a        = (int)(Random.Range(0, matingPool.Count));
         int     b        = (int)(Random.Range(0, matingPool.Count));
         DNAchar partnerA = matingPool[a];
         DNAchar partnerB = matingPool[b];
         DNAchar child    = partnerA.crossover(partnerB);
         child.mutate(mutationRate);
         population[i] = child;
     }
     generations++;
 }
コード例 #2
0
    public Population(string p, float m, int num)
    {
        target       = p;
        mutationRate = m;
        population   = new DNAchar[num];
        for (int i = 0; i < population.Length; i++)
        {
            population[i] = new DNAchar(target.Length);
        }
        calcFitness();
        matingPool  = new List <DNAchar>();
        finished    = false;
        generations = 0;

        perfectScore = 1;
    }
コード例 #3
0
    // Crossover
    public DNAchar crossover(DNAchar partner)
    {
        // A new child
        DNAchar child = new DNAchar(genes.Length);

        int midpoint = (int)(Random.Range(0, genes.Length)); // Pick a midpoint

        // Half from one, half from the other
        for (int i = 0; i < genes.Length; i++)
        {
            if (i > midpoint)
            {
                child.genes[i] = genes[i];
            }
            else
            {
                child.genes[i] = partner.genes[i];
            }
        }
        return(child);
    }
コード例 #4
0
    public void generate()
    {
        // Refill the population with children from the mating pool
        for (int i = 0; i < population.Length; i++)
        {
            int a = (int)(Random.Range(0, matingPool.Count));
            int b = (int)(Random.Range(0, matingPool.Count));

            //exercise9.4 two unique 'parents'
            if (a == b)
            {
                b = b + (b > 0.5 * matingPool.Count ? -1 : 1);
            }


            DNAchar partnerA = matingPool[a];
            DNAchar partnerB = matingPool[b];
            DNAchar child    = partnerA.crossover(partnerB);
            child.mutate(mutationRate);
            population[i] = child;
        }
        generations++;
    }