I am trying to implement genetic algorithm for permutation problem. I have a file with results of tests and faults which were found during the tests, I need to find the optimal way to permutate the tests.
I need some crossover function to mate genes of the fittest and second fittest chromosomes, which are the lists of strings, the strings are keys in LinkedHashMap, so the lists should contain the same set of strings, but in a different order.
For instance,
“t1”, “t4”, “t2”, “t3”, “t0”
or
“t4”, “t3”, “t2”, “t1”, “t0”
My code:
static void crossover() {
//Select a random crossover point
int crossOverPoint = rand.nextInt(population.chromosomes[0].genes.size());
//
System.out.println("it's crossover time");
System.out.println("crossover point " + crossOverPoint);
System.out.println("fittest before " + fittest.genes);
System.out.println("second fittest " + secondFittest.genes);
//
//Swap values among parents
for (int i = 0; i < crossOverPoint; i++) {
String temp = fittest.genes.get(i);
fittest.genes.set(i, secondFittest.genes.get(i));
secondFittest.genes.set(i, temp);
}
System.out.println("fittest after " + fittest.genes);
System.out.println("second fittest after " + secondFittest.genes);
}
I have created a function which for random crossover point replaces elements of the lists, but I need to make the sets valid – all elements should be unique to avoid doubled keys in the LinkedHashMap. For instance,
If I have the fittest and second fittest,
“t1”, “t4”, “t2”, “t3”, “t0”
“t4”, “t3”, “t2”, “t1”, “t0”
And crossing point 2, I will get following offspring
“t1”, “t4” |”t2”, “t1”, “t0”
“t4”, “t3”, |“t2”, “t3”, “t0”
And both will become invalid because we have doubled key “t1” in the first and no “t3”, and second has doubled “t3” and no “t1”
Would appreciate any help. Thank you.