用于重新生成人口的复杂循环

时间:2013-11-22 18:09:07

标签: java for-loop iterator genetic-algorithm

我正在使用遗传算法,我正在尝试在群体中重新创建个体(在生成结束时删除它们之后)。问题是'crossover'函数创建了两个人,'mutate'和'createRandomIndividual'函数创建了一个人。我怎么能在循环中加入它?

List<Individual> population = new ArrayList<Individual>();

private void replaceIndividuals(int individualsTurnover) {
    //individualTurnover = number of individuals I need to re-generate
    boolean even = individualsTurnover % 2 == 0;

    for (int i=0; i<individualsTurnover/2; i++){
        replaceIndividuals();
    }

    if (!even)
        mutate();
}

private void replaceIndividuals() {
    int random = generator.nextInt(10);

    if (random < 1) {
        // generates one individual via mutation
        mutate(); 
    }
    else if (random < 2) {
        // generates one individual randomly
        createRandomIndividual();
    }
    else  {
        //generates two individuals by crossing-over individuals from a pool of parents
        crossover();
    }
}

目前正在创建太多人。创建的个人数量应为='individualTurnover'。

1 个答案:

答案 0 :(得分:0)

这可能会解决您的问题。我稍微改变了方法签名

 public class Test
    {

        private void replaceIndividuals(int individualsTurnover) {
            //individualTurnover = number of individuals I need to re-generate
           while(individualsTurnover > 1)
           {
               individualsTurnover = individualsTurnover - replaceIndividuals();
               //I am deducting this count because those many individuals are already created
           }
           //This is the only possible count > 0
           if(individualsTurnover == 1)
           {
               mutate();
           }
        }
        /**
         * 
         * @return No of individulas created
         */
        private int  replaceIndividuals() {
            int random = generator.nextInt(10);

            if (random < 1) {
                // generates one individual via mutation
                mutate();
                retrun 1;
            }
            else if (random < 2) {
                // generates one individual randomly
                createRandomIndividual();
                return 1;
            }
            else  {
                //generates two individuals by crossing-over individuals from a pool of parents
                crossover();

                return 2;
            }
        }
    }