I did this code for somebody but need it to be double checked before I pass it onto them. Code seems fine but I need someone to confirm I have coded the crossover methods correctly.
Would be great if somebody that is familiar with genetic algorithms and crossover methods, could confirm that I have the correct logic and code behind each crossover method.
//one crossover point is selected, string from beginning of chromosome to the
//crossover point is copied from one parent, the rest is copied from the second parent
// One-point crossover
public void onePointCrossover(Individual indi) {
if (SGA.rand.nextDouble() < pc) {
// choose the crossover point
int xoverpoint = SGA.rand.nextInt(length);
int tmp;
for (int i=xoverpoint; i<length; i++){
tmp = chromosome[i];
chromosome[i] = indi.chromosome[i];
indi.chromosome[i] = tmp;
}
}
}
//two crossover point are selected, binary string from beginning of chromosome to
//the first crossover point is copied from one parent, the part from
// the first to the second crossover point is copied from the second parent
// and the rest is copied from the first parent
// Two-point crossover
public void twoPointCrossover(Individual indi) {
if (SGA.rand.nextDouble() < pc) {
// choose the crossover point
int xoverpoint = SGA.rand.nextInt(length);
int xoverpoint2 = SGA.rand.nextInt(length);
int tmp;
//swap
if (xoverpoint > xoverpoint2){
tmp = xoverpoint;
xoverpoint = xoverpoint2;
xoverpoint2 = tmp;
}
for (int i=xoverpoint; i<xoverpoint2; i++){
tmp = chromosome[i];
chromosome[i] = indi.chromosome[i];
indi.chromosome[i] = tmp;
}
}
}
// For each gene, create a random number in [0,1]. If
// the number is less than 0.5, swap the gene values in
// the parents for this gene; otherwise, no swapping
// Uniform Crossover
public void UniformCrossover(Individual indi) {
if (SGA.rand.nextDouble() < pc) {
for (int i= 1; i<length; i++){
boolean tmp = SGA.rand.nextFloat() < 0.5;
if(tmp){
chromosome[i] = indi.chromosome[i];
}
}
}
Parent 1 = chromosome Parent 2= indi.chromosome
I am turning the parents into children inplace.