I've been working on different genetic algorithm selection methods recently. At the moment I have a RawFitnessSelction class, a RouletteWheelSelection class and a TournamentSelection class. I've been asked to use a factory/abstract factory pattern to choose the different selection methods. I think I'm going to go with a factory pattern as I don't fully understand abstract factory patterns but I'm wondering how to apply the actual pattern to something like GA selection methods?
public static Map<String, Double> rouletteSelect (Map<String, Double> population) {
//Create a List (ArrayList) called rouletteSelect of type
//Map<String, Double> and input values from our input Map.
List<Map.Entry<String,Double>> sorted = new ArrayList<>(population.entrySet());
//Use collections.sort to sort our "sorted" base on their values
Collections.sort(sorted, Comparator.comparing(Map.Entry::getValue));
//Initialize a HashSet
Set<Integer> usedIndices = new HashSet<>();
//Initialize our result Map<>, to store our selected individuals
Map<String, Double> result = new HashMap<>();
//we want to "select" half the individuals so while the size of our result
//is less than half, keep going
while (result.size() < sorted.size()/2) {
//pick a random int between 0 and the number of elements we have
int index = rnd.nextInt(sorted.size());
//if the element isn't in our set (a set can only contain one
//occurrence of value x) do what is after our if, else it increments
//our while loop (it's already in our set)
if(!usedIndices.add(index)) {
continue;
}
//create a new Map, which has the <key,vale> of corresponding
//index of "index" in sorted ArrayList
Map.Entry<String, Double> survivor =sorted.get(index);
//pur key and value from survivor into our result HashMap.
result.put(survivor.getKey(), survivor.getValue());
}
return result;
}
Here's the basic structure of my selection methods. Just a basic method stored inside a class. Any help on how to implement the factory pattern to these types of methods would be appreciated.
Note: I know what my actual factory.java file will look like it's more so the abstact Selection.java class and the subclass RouletteWheel.java. Thanks