I am using Jenetics
library to solve a problem with ga. I am extending the official example to use several chromosomes like this:
List<BitChromosome> arr = new ArrayList<>();
arr.add(BitChromosome.of(16, 0.5));
arr.add(BitChromosome.of(16, 0.5));
arr.add(BitChromosome.of(16, 0.5));
Factory<Genotype<BitGene>> gtf = Genotype.of(arr);
And change the eval
function to have exactly 8 1s and 8 0s:
private static int eval(Genotype<BitGene> gt) {
return 10 - Math.abs(gt.getChromosome()
.as(BitChromosome.class)
.bitCount()-8);
The other parts were left unchanged:
// 3.) Create the execution environment.
Engine<BitGene, Integer> engine = Engine
.builder(Test1::eval, gtf)
.build();
// 4.) Start the execution (evolution) and
// collect the result.
Genotype<BitGene> result = engine.stream()
.limit(100)
.collect(EvolutionResult.toBestGenotype());
I was expecting the ga go produce 3 chromosomes which maximize this eval function but I am getting:
[01110010|00010111,01000000|00000100,10011101|01110110]
As you can see, only the first result satisfy the condition. How can I extend this example so all chromosomes will maximize the evaluation function?
This is exactly what I would expect after looking at the fitness function. You are using only the first chromosome for calculating the fitness. The Genotype.getChromosome()
method returns the first chromosome. It is a shortcut for Genotype.getChromosome(0)
. The other two chromosomes are not considered in your fitness function.