patternjavaMinor
Confirm code is correct - crossover methods in Java
Viewed 0 times
confirmjavamethodscrossovercorrectcode
Problem
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.
Parent 1 = chromosome Parent 2= indi.chromosome
I am turning the parents into children inplace.
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() 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.
Solution
It's difficult to just look at, but a few things jump out. More improvements than bugs:
-
For single point crossover using
-
You could use the same method for two point, but it would be slightly more complex.
-
In Uniform crossover you can use
-
For single point crossover using
System.arraycopy() would be much more reliable. For example:System.arraycopy(parent1Genes, 0, childGenes, 0, xoverPoint);
System.arraycopy(parent2Genes, xoverPoint, childGenes, xoverPoint, geneSize-xoverPoint);-
You could use the same method for two point, but it would be slightly more complex.
-
In Uniform crossover you can use
rand.nextBoolean(), which returns true or false, instead of comparing the float.Code Snippets
System.arraycopy(parent1Genes, 0, childGenes, 0, xoverPoint);
System.arraycopy(parent2Genes, xoverPoint, childGenes, xoverPoint, geneSize-xoverPoint);Context
StackExchange Code Review Q#9077, answer score: 4
Revisions (0)
No revisions yet.