PartiallyMatchedCrossover extends Crossover<EnumGene<T>, C> { @Override protected int crossover( final MSeq<EnumGene<T>> that, final MSeq<EnumGene<T>> other ) { if (that.length() != other.length()) { throw new IllegalArgumentException(format( "Required chromosomes with same length: %s != %s", that.length(), other.length() )); } if (that.length() >= 2) { final Random random = RandomRegistry.random(); final int[] points = Combinatorics.subset(that.length(), 2, random); that.swap(points[0], points[1], other, points[0]); repair(that, other, points[0], points[1]); repair(other, that, points[0], points[1]); } return 1; } PartiallyMatchedCrossover(final double probability); @Override String toString();  }
@Test(invocationCount = 10) public void crossover() { final PartiallyMatchedCrossover<Integer, Double> pmco = new PartiallyMatchedCrossover<>(1); final int length = 1000; final MSeq<Integer> alleles = MSeq.<Integer>ofLength(length).fill(Int()); final ISeq<Integer> ialleles = alleles.toISeq(); final MSeq<EnumGene<Integer>> that = alleles.map(i -> new EnumGene<>(i, ialleles)); final MSeq<EnumGene<Integer>> other = alleles.map(i -> new EnumGene<>(i, ialleles)); that.shuffle(); other.shuffle(); final PermutationChromosome<Integer> thatChrom1 = new PermutationChromosome<>(that.toISeq()); Assert.assertTrue(thatChrom1.isValid(), "thatChrom1 not valid"); final PermutationChromosome<Integer> otherChrom1 = new PermutationChromosome<>(other.toISeq()); Assert.assertTrue(otherChrom1.isValid(), "otherChrom1 not valid"); pmco.crossover(that, other); final PermutationChromosome<Integer> thatChrom2 = new PermutationChromosome<>(that.toISeq()); Assert.assertTrue(thatChrom2.isValid(), "thatChrom2 not valid: " + thatChrom2); final PermutationChromosome<Integer> otherChrom2 = new PermutationChromosome<>(other.toISeq()); Assert.assertTrue(otherChrom2.isValid(), "otherChrom2 not valid: " + otherChrom2); Assert.assertFalse(thatChrom1.equals(thatChrom2), "That chromosome must not be equal"); Assert.assertFalse(otherChrom1.equals(otherChrom2), "That chromosome must not be equal"); }
@Test public void crossoverWithIllegalChromosome() { final PartiallyMatchedCrossover<Integer, Double> pmco = new PartiallyMatchedCrossover<>(1); final int length = 1000; final MSeq<Integer> alleles = MSeq.<Integer>ofLength(length).fill(Int()); final ISeq<Integer> ialleles = alleles.toISeq(); final MSeq<EnumGene<Integer>> that = alleles.map(i -> new EnumGene<>(i, ialleles)); final MSeq<EnumGene<Integer>> other = alleles.map(i -> new EnumGene<>(i, ialleles)); pmco.crossover(that, other); }