【发布时间】:2018-10-29 08:00:48
【问题描述】:
我创建了新的染色体并添加到列表中(我确定染色体是不同的,因为我在添加之前已经打印了它们)但是最后当我打印列表或获取随机索引时,只有最后两条染色体。(通常在交互过程中,我从当前一代的两条随机染色体中创建两条新染色体,以便通过交叉创建新一代)。
public Population crossoverChromosomes(Population population, List<Item> items, int capacityOfKnapsack) {
Random rand = new Random();
List<Chromosome> chromosomeList = new ArrayList<>(population.getChromosomeList());
int genesLength = population.chromosomeList.get(0).getGenes().length;
int newGenes1[] = new int[genesLength];
int newGenes2[] = new int[genesLength];
ArrayList<Chromosome> newCrossoverPopulation = new ArrayList<>();
for (int j = 0; j < population.getPopulationSize() / 2; j++) {
int firstChrIndex = rand.nextInt(population.getPopulationSize() - 1);
int secondChrIndex = rand.nextInt(population.getPopulationSize() - 1);
int d = rand.nextInt(population.getPopulationSize() - 1);
Chromosome firstChr = chromosomeList.get(firstChrIndex);
Chromosome secondChr = chromosomeList.get(secondChrIndex);
for (int i = 0; i < genesLength; i++) {
if (i < d) {
newGenes1[i] = firstChr.getGenes()[i];
newGenes2[i] = secondChr.getGenes()[i];
} else {
newGenes1[i] = secondChr.getGenes()[i];
newGenes2[i] = firstChr.getGenes()[i];
}
}
Chromosome chr1 = new Chromosome(genesLength, newGenes1);
Chromosome chr2 = new Chromosome(genesLength, newGenes2);
chr1.fitnessCalculate(items, capacityOfKnapsack);
newCrossoverPopulation.add(chr1);
chr2.fitnessCalculate(items, capacityOfKnapsack);
newCrossoverPopulation.add(chr2);
}
return new Population(newCrossoverPopulation.size(), newCrossoverPopulation);
}
【问题讨论】:
-
你尝试调试了吗?
标签: java list object arraylist genetic-algorithm