1 package net.bmahe.genetics4j.core.replacement; 2 3 import java.util.Comparator; 4 import java.util.List; 5 import java.util.stream.IntStream; 6 7 import org.apache.commons.lang3.Validate; 8 9 import net.bmahe.genetics4j.core.Genotype; 10 import net.bmahe.genetics4j.core.Population; 11 import net.bmahe.genetics4j.core.selection.Selector; 12 import net.bmahe.genetics4j.core.spec.AbstractEAConfiguration; 13 import net.bmahe.genetics4j.core.spec.replacement.DeleteNLast; 14 15 public class DeleteNLastImpl<T extends Comparable<T>> implements ReplacementStrategyImplementor<T> { 16 17 private final DeleteNLast deleteNLastSpec; 18 private final Selector<T> offspringSelector; 19 20 public DeleteNLastImpl(final DeleteNLast _deleteNLastSpec, final Selector<T> _offspringSelector) { 21 Validate.notNull(_deleteNLastSpec); 22 Validate.notNull(_offspringSelector); 23 24 this.deleteNLastSpec = _deleteNLastSpec; 25 this.offspringSelector = _offspringSelector; 26 } 27 28 @Override 29 public Population<T> select(final AbstractEAConfiguration<T> eaConfiguration, final int numIndividuals, 30 final List<Genotype> population, final List<T> populationScores, final List<Genotype> offsprings, 31 final List<T> offspringScores) { 32 Validate.notNull(eaConfiguration); 33 Validate.isTrue(numIndividuals > 0); 34 Validate.notNull(population); 35 Validate.notNull(populationScores); 36 Validate.isTrue(population.size() == populationScores.size()); 37 Validate.notNull(offsprings); 38 Validate.notNull(offspringScores); 39 Validate.isTrue(offsprings.size() == offspringScores.size()); 40 41 final Comparator<T> populationComparator = eaConfiguration.fitnessComparator(); 42 43 final Population<T> selected = new Population<>(); 44 45 final int weakestN = (int) (numIndividuals * deleteNLastSpec.weakRatio()); 46 47 IntStream.range(0, populationScores.size()) 48 .boxed() 49 .sorted((a, b) -> populationComparator.compare(populationScores.get(a), populationScores.get(b))) 50 .skip(weakestN) 51 .forEach(index -> { 52 selected.add(population.get(index), populationScores.get(index)); 53 }); 54 55 final Population<T> selectedOffspring = offspringSelector 56 .select(eaConfiguration, weakestN, offsprings, offspringScores); 57 selected.addAll(selectedOffspring); 58 59 return selected; 60 } 61 }