1

How would I implement a Uniform Crossover method in Java for a Genetic Algorithm?

Currently, I am using 2 ArrayLists which need to be interconnected before the program continues. Below is the start of the method I have been using:

private void UniformCrossOver(int ListOne,int ListTwo)
{
...
}

Where I stand at the moment, I am assuming that I will need to make another 2 ArrayLists which will have the data split into but I have no idea where to start with the crossover. Would I use a for loop with the size of the new arrays being the defining key?

Your help would be greatly appreciated.

Kieron MK
  • 75
  • 8
  • http://stackoverflow.com/questions/9318881/uniform-crossover-in-java – David Choweller Mar 11 '17 at 15:23
  • You need one `ArrayList` to store the result. At each point, you randomly choose an element from one of the two input `ArrayLists` with 0.5 probability. You can do this by using a random number generator to choose between 0 and 1, say (`Random::nextInt(0,2)`). You store the resulting element in the result arrayList. – David Choweller Mar 11 '17 at 15:28
  • Ok. So would that mean I need to create in incrementing `for` loop which runs for each element in the `ArrayList`. I.e: the random number generator is the element of uncertainty which makes the decision on whether a new node is taken from parent A or parent B? – Kieron MK Mar 11 '17 at 15:34
  • Yes. If the length of the two input lists is different (I'm not sure if that is a possibility in your scenario) you have to decide what to do in that case. – David Choweller Mar 11 '17 at 15:51
  • Possible duplicate of [Uniform Crossover in Java](http://stackoverflow.com/questions/9318881/uniform-crossover-in-java) – Grzegorz Górkiewicz Mar 11 '17 at 15:56

2 Answers2

0

You don't have to make new array lists if you don't need parents after crossover. This should work as long your chromosomes are of equal size

public void uniformCrossover(ArrayList<Integer> a, ArrayList<Integer> b){
    for (int i = 0; i <a.size(); i++) {
        if(Math.random() < crossoverProbability){
            int tmp = a.get(i);
            a.set(i, b.get(i));
            b.set(i, tmp);
        }
    }
}
Michael Dz
  • 3,655
  • 8
  • 40
  • 74
0

You can make it using arrays

//Some example chromosomes
int[] chromosomeA = {1, 1, 0, 1};
Int[] chromosomeB = {1, 0, 0, 0};

    for(int i = 0; i < chromosomeA.length; i++){
       int a = chromosomeA[i];
       if(new Random().nextInt(2) == 0){
         chromosomeA[i] = chromosomeB[i];
         chromosomeB[i] = a;
       }
    }