I'm trying to learn about genetic algorithms and am currently working on "crossing over" two "genes". A gene is an integer array, consisting of ones and zeros. To exemplify my problem let's say we have two genes.
int[] geneA = {1,0,0,0,0};
int[] geneB = {0,1,1,1,0};
The expected result from a cross-over, for example at position 3 would be:
geneA = [1,0,0,1,0]
geneB = [0,1,1,0,0]
Meaning that every element at the index of 3 or above would be swapped with the equivalent element of the other gene. To achieve this I wrote the following method:
private void crossOver(int[] geneA, int[] geneB, int pos) {
int copyA[];
int copyB[];
copyA = geneA;
copyB = geneB;
for(int i = pos; i < geneA.length; i++) {
geneA[i] = copyB[i];
geneB[i] = copyA[i];
}
System.out.println(Arrays.toString(geneA);
System.out.println(Arrays.toString(geneB);
}
However, it seems that the elements of geneB simply get copied into geneA at the index of 3 or higher. The console output is as following:
[1, 0, 0, 1, 0]
[0, 1, 1, 1, 0]
Any explanations or help are highly appreciated. Thanks in advance!
copyA = geneA
does not create a copy. Both variables now refer to the same array.
There is no need to waste time and space on copying the entire array.
When you swap values, you just need to store one of the values in a temporary variable.
private static void crossOver(int[] geneA, int[] geneB, int pos) {
for (int i = pos; i < geneA.length; i++) {
int temp = geneA[i];
geneA[i] = geneB[i];
geneB[i] = temp;
}
}
That will update the arrays in-place, so the caller will see the change.
int[] geneA = {1,0,0,0,0};
int[] geneB = {0,1,1,1,0};
crossOver(geneA, geneB, 3);
System.out.println(Arrays.toString(geneA));
System.out.println(Arrays.toString(geneB));
Output
[1, 0, 0, 1, 0]
[0, 1, 1, 0, 0]