1 package net.bmahe.genetics4j.core.combination.singlepointarithmetic; 2 3 import java.util.List; 4 import java.util.random.RandomGenerator; 5 6 import org.apache.commons.lang3.Validate; 7 8 import net.bmahe.genetics4j.core.chromosomes.Chromosome; 9 import net.bmahe.genetics4j.core.chromosomes.IntChromosome; 10 import net.bmahe.genetics4j.core.combination.ChromosomeCombinator; 11 import net.bmahe.genetics4j.core.spec.AbstractEAConfiguration; 12 13 public class IntChromosomeSinglePointArithmetic<T extends Comparable<T>> implements ChromosomeCombinator<T> { 14 15 private final RandomGenerator randomGenerator; 16 private final double alpha; 17 18 public IntChromosomeSinglePointArithmetic(final RandomGenerator _randomGenerator, final double _alpha) { 19 Validate.notNull(_randomGenerator); 20 Validate.inclusiveBetween(0.0d, 1.0d, _alpha); 21 22 this.randomGenerator = _randomGenerator; 23 this.alpha = _alpha; 24 } 25 26 @Override 27 public List<Chromosome> combine(final AbstractEAConfiguration<T> eaConfiguration, final Chromosome chromosome1, 28 final T firstParentFitness, final Chromosome chromosome2, final T secondParentFitness) { 29 Validate.notNull(chromosome1); 30 Validate.notNull(chromosome2); 31 Validate.isInstanceOf(IntChromosome.class, chromosome1); 32 Validate.isInstanceOf(IntChromosome.class, chromosome2); 33 Validate.isTrue(chromosome1.getNumAlleles() == chromosome2.getNumAlleles()); 34 35 final int alleleSplit = randomGenerator.nextInt(chromosome1.getNumAlleles()); 36 37 final IntChromosome intChromosome1 = (IntChromosome) chromosome1; 38 final IntChromosome intChromosome2 = (IntChromosome) chromosome2; 39 40 final int numAlleles = chromosome1.getNumAlleles(); 41 final int[] firstChildValues = new int[numAlleles]; 42 final int[] secondChildValues = new int[numAlleles]; 43 44 for (int i = 0; i < numAlleles; i++) { 45 46 final int firstAllele = intChromosome1.getAllele(i); 47 final int secondAllele = intChromosome2.getAllele(i); 48 49 if (i < alleleSplit) { 50 firstChildValues[i] = (int) (alpha * firstAllele + (1 - alpha) * secondAllele); 51 secondChildValues[i] = (int) ((1 - alpha) * firstAllele + alpha * secondAllele); 52 } else { 53 firstChildValues[i] = (int) ((1 - alpha) * firstAllele + alpha * secondAllele); 54 secondChildValues[i] = (int) (alpha * firstAllele + (1 - alpha) * secondAllele); 55 } 56 } 57 58 return List.of( 59 new IntChromosome(numAlleles, intChromosome1.getMinValue(), intChromosome1.getMaxValue(), firstChildValues), 60 new IntChromosome(numAlleles, 61 intChromosome1.getMinValue(), 62 intChromosome1.getMaxValue(), 63 secondChildValues)); 64 } 65 }