BinaryMutation implements MutationPolicy { public Chromosome mutate(Chromosome original) throws MathIllegalArgumentException { if (!(original instanceof BinaryChromosome)) { throw new MathIllegalArgumentException(LocalizedFormats.INVALID_BINARY_CHROMOSOME); } BinaryChromosome origChrom = (BinaryChromosome) original; List<Integer> newRepr = new ArrayList<Integer>(origChrom.getRepresentation()); int geneIndex = GeneticAlgorithm.getRandomGenerator().nextInt(origChrom.getLength()); newRepr.set(geneIndex, origChrom.getRepresentation().get(geneIndex) == 0 ? 1 : 0); Chromosome newChrom = origChrom.newFixedLengthChromosome(newRepr); return newChrom; }  Chromosome mutate(Chromosome original);  }
@Test public void testMutate() { BinaryMutation mutation = new BinaryMutation(); for (int i=0; i<20; i++) { DummyBinaryChromosome original = new DummyBinaryChromosome(BinaryChromosome.randomBinaryRepresentation(10)); DummyBinaryChromosome mutated = (DummyBinaryChromosome) mutation.mutate(original); int numDifferent = 0; for (int j=0; j<original.getRepresentation().size(); j++) { if (original.getRepresentation().get(j) != mutated.getRepresentation().get(j)) numDifferent++; } Assert.assertEquals(1, numDifferent); } }