所以基本上我正在创建一个遗传算法,但是在实现交叉代码时我被卡住了。任何人都可以伸出援助之手,让我知道我的代码在实施订单一交叉时是否朝着正确的方向迈出了一步。或者任何人都可以给我订购一个交叉的伪代码吗?
package geneticalgorithm;
import java.util.Random;
public class GeneticAlgorithm {
final static int P = 20;
final static int N = 10;
static int popFitness = 0;
int offspringFitness = 0;
static Random rand = new Random();
static int count = 0;
static Individual[] population = new Individual[P];
static Individual[] offspring = new Individual[P];
public static void main(String[] args) {
for (int i = 0; i < P; i++){
population[i] = new Individual(); //Generates a population of P individuals and gives each one unique genes
population[i].generateGenes();
population[i].fitness = 0;
}
for (int i = 0; i < P; i++){
for (int j = 0; j < N; j++){ // Loops through each individual in the population and assesses their
if (population[i].genes[j] == 1 ){ //fitness based on how many 1's are in its genes
population[i].fitness++;
}
}
}
for (int i = 0; i < P ; i++){
for (int j = 0; j < N; j++){
count++;
System.out.print(population[i].genes[j] ); // Loops through population and each gene and outputs each individuals genes to the screen aswell as there fitness
if ((count % N) == 0){
System.out.print( " " + population[i].fitness);
System.out.println("");
}
}
}
for (int i = 0; i < P; i++){
popFitness += population[i].fitness; // calculates the overall fitness of the population
}
System.out.println(popFitness);
offspring[1] = population[rouletteSelection()];
System.out.println(offspring[1]);
for (int i = 0; i < P; i++){
int p1 = rand.nextInt(P);
int p2 = rand.nextInt(P);
if (population[p1].fitness >= population[p2].fitness){
offspring[i] = population[p1];
}
else { //Randomly creates a new population called offspring by comparing two random parents
offspring[i] = population[p2]; //and picking the one with the largest fitness value
}
}
}
public static Individual crossover1(Individual parent1, Individual parent2){
Individual newSol = new Individual();
parent1 = population[rouletteSelection()];
parent2 = population[rouletteSelection()];
int crossoverPoint = rand.nextInt(N);
for (int j = 0; j < N; j++){
Individual newSolution = new Individual();
for (int i = 0; i == crossoverPoint; i++){
newSolution.setGenes(i, parent1.getGenes(i));
}
for (int i = crossoverPoint; i < N; i++){
newSolution.setGenes(i, parent2.getGenes(i));
}
}
return null;}
public static int rouletteSelection(){
int parent = 0;
int randNum = rand.nextInt(popFitness);
int rollingSum = 0;
for (int i = 0; i < P; i++){
rollingSum += population[i].fitness; //Algorithm to select a parent based on probability and a hint of randomness
if (rollingSum >= randNum){
parent = i;
break;
}
} System.out.println(parent);
return parent;
}
}