Search code examples
javaalgorithmcomputer-sciencegenetic-algorithm

Uniform Crossover for Genetic Algorithms in Java


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.


Solution

  • 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);
            }
        }
    }