예제 #1
0
    public static GAPopulation generate(GAPopulation p, int xrate, int mrate)
    {
        // Generate a new population from p, xrate percent of the induviduals
        // of new population are generated by cross-over, mrate percent of them are
        // generated by mutation, and others by reproduction.

        if (xrate < 0 || xrate > 100 || mrate < 0 || mrate > 100 || xrate + mrate > 100)
        {
            Console.Error.WriteLine("error: xrate and/or mrate are not properly set");
        }

        GAIndividual[] newg       = new GAIndividual[p.pop_size];
        int            newg_index = 0;

        int xn = xrate * p.pop_size / 100;         // xn: number of offsprings to be produced by xover
        int mn = mrate * p.pop_size / 100;         // mn: number of offsprings to be produced by mutation

        // xover:
        for (int i = 0; i < xn; i++)
        {
            // select two parents for cross-over:
            // we want two distinct parents (i.e. p1 != p2)
            int p1, p2;
            do
            {
                p1 = p.tr_select();
                p2 = p.tr_select();
            }while (p1 == p2);

            newg[newg_index++] = GAIndividual.xover1p(p.ind[p1], p.ind[p2]);
        }

        // mutation:
        for (int i = 0; i < mn; i++)
        {
            newg[newg_index++] = p.ind[p.tr_select()].mutate();
        }

        // reproduction:
        for (int i = newg_index; i < p.pop_size; i++)
        {
            newg[i] = p.ind[p.tr_select()];
        }

        return(new GAPopulation(newg));
    }