public void startCrossover() { for (int i = 0; i < popSize; i++) { // test the probability is larger than crossoverRate. if (Math.random() <= crossoverRate) { int cutPoint = (int) (Math.random() * chromosomeLength); // to get the other chromosome to crossover int index2 = getCrossoverChromosome(i); copyElements(i, index2, cutPoint); copyElements(index2, i, cutPoint); } } }
/** * To get the other chromosome to crossover. * * @param index The index of original chromosome. * @return */ public final int getCrossoverChromosome(int index) { int index2 = (int) (Math.random() * popSize); if (index == index2) { index2 = getCrossoverChromosome(index); } return index2; }
private int[] generateRandomVector() { int vector1[] = new int[chromosomeLength]; for (int i = 0; i < chromosomeLength; i++) { if (Math.random() > 0.5) { vector1[i] = 1; } else { vector1[i] = 0; } } return vector1; }
public void startCrossover() { calcAdaptiveParameter(); for (int i = 0; i < popSize; i++) { if (originalPop.getFitness(i) < avgFitness) { crossoverRate = k1 * (newPop.getFitness(i) - minFitness) / (avgFitness - minFitness); } else { crossoverRate = k3; } // test the probability is larger than crossoverRate. if (Math.random() <= crossoverRate) { // to get the other chromosome to crossover int index2 = getCrossoverChromosome(i); int vector1[] = generateRandomVector(); copyElements(i, index2, vector1); copyElements(index2, i, vector1); } } }