Я создаю новые хромосомы и добавляю в список (я уверен, что хромосомы отличаются, потому что я напечатал их перед добавлением), но в конце, когда я печатаю список или получаю случайный индекс, остаются только две последние хромосомы. (Обычново время взаимодействия я создаю две новые хромосомы из двух случайных хромосом из текущего поколения, чтобы создать новое поколение посредством кроссовера).
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);
}