I implemented the Multiparental Sorting Crossover as described here in section 4.2. The (compiled) program can be run as follows:
$ java MPSX input.txt
where input.txt looks like this (the first line is the mask followed by three parents):
3 1 2 1 1 1 1 2 2
8 4 7 3 6 2 5 1 9
9 1 2 3 4 5 6 7 8
4 7 9 3 6 2 5 1 8
As for output, it merely prints the correct result as a string.
import edu.princeton.cs.algs4.In;
import java.io.InputStream;
public class MPSX {
public static void main(String[] args) {
String filename = args[0];
In in = new In(filename);
String[] Input = in.readAllLines();
String result = solve(Input);
System.out.println(result);
}
private static void swap(int[] parent_x, int[] parent_y, int index) {
for (int i = 0; i < parent_y.length; i++) {
if (parent_y[i] == parent_x[index]) {
int tmp = parent_y[index];
parent_y[index] = parent_y[i];
parent_y[i] = tmp;
}
}
}
private static String solve(String[] Input) {
String result = "";
String[] parent1str = Input[1].split(" ");
String[] parent2str = Input[2].split(" ");
String[] parent3str = Input[3].split(" ");
int[] parent1 = new int[parent1str.length];
int[] parent2 = new int[parent2str.length];
int[] parent3 = new int[parent3str.length];
for (int i = 0; i < parent1str.length; i++) {
parent1[i] = Integer.parseInt(parent1str[i]);
parent2[i] = Integer.parseInt(parent2str[i]);
parent3[i] = Integer.parseInt(parent3str[i]);
}
String mask = Input[0].replaceAll("\\s","");
for (int i = 0; i < mask.length(); i++) {
int mask_element = Character.getNumericValue(mask.charAt(i));;
if (mask_element == 1) {
result += parent1[i];
swap(parent1, parent2,i);
swap(parent1, parent3,i);
}
else if (mask_element == 2) {
result += parent2[i];
swap(parent2, parent1,i);
swap(parent2, parent3,i);
}
else if (mask_element == 3) {
result += parent3[i];
swap(parent3, parent1,i);
swap(parent3, parent2,i);
}
}
return result;
}
}
It is effectively the first program I wrote in Java so I know there is a lot of room for improvement and refactorization.
In particular, I am sure there is a better (more concise) way of processing the input text file. I thought of creating an array of arrays of Strings instead of 3 separate arrays but I wasn't sure how to do it.