diff --git a/src/main/java/MainClasses/GeneticAlgorithm.java b/src/main/java/MainClasses/GeneticAlgorithm.java index 9159e5d644a455491c3d6d5a09fdb312d99bebe3..98840fa775ce875333f63e7b49bd00ba65ced474 100644 --- a/src/main/java/MainClasses/GeneticAlgorithm.java +++ b/src/main/java/MainClasses/GeneticAlgorithm.java @@ -122,7 +122,7 @@ public class GeneticAlgorithm { } if (config.getSelectionMethod().equals(SelectionMethods.Proportional)) { - this.selector = new FitnessProportional(this.rand, this.isHydrophobic); + this.selector = new FitnessProportional(this.config, this.rand); } else if (config.getSelectionMethod().equals(SelectionMethods.Tournament)) { this.selector = new Tournament(this.rand, this.isHydrophobic, config.getK()); } else if (config.getSelectionMethod().equals(SelectionMethods.OnlyBest)) { diff --git a/src/main/java/Selectors/FitnessProportional.java b/src/main/java/Selectors/FitnessProportional.java index 57b5b805a9e3ff13af997be64ef431966fcbac2e..76439d5f645f69c100e601c37573c73b2c409ed6 100644 --- a/src/main/java/Selectors/FitnessProportional.java +++ b/src/main/java/Selectors/FitnessProportional.java @@ -3,37 +3,40 @@ package Selectors; import Interfaces.Selector; import MainClasses.Candidate; +import MainClasses.Config; import java.util.Random; public class FitnessProportional implements Selector { Random rand; - int[] isHydrophobic; + Config config; - public FitnessProportional(Random rand, int[] isHydrophobic) { + public FitnessProportional(Config config, Random rand) { this.rand = rand; - this.isHydrophobic = isHydrophobic; + this.config = config; } @Override - public Candidate[] selectNewPopulation(Candidate[] population, double[] fitness, double totalFitness) { - int populationSize = population.length; + public Candidate[] selectNewPopulation(Candidate[] generation) { + int populationSize = generation.length; - // Pick set for next generation - double[] proportionalFitness = new double[populationSize]; - for (int i = 0; i < populationSize; i++) { - proportionalFitness[i] = fitness[i] / totalFitness; + double totalFitness = 0.0; + for (Candidate candidate: generation) { + totalFitness += candidate.getFitness(); } Candidate[] newPopulation = new Candidate[populationSize]; for (int i = 0; i < populationSize; i++) { - double picked = rand.nextDouble(); - int j = -1; - while (picked > 0) { - j++; - picked -= proportionalFitness[j]; + //Select a number between 0 and the maximum fitness + double requiredFitness = rand.nextDouble() * totalFitness; + double currentFitness = 0.0; + for (Candidate candidate : generation) { + currentFitness += candidate.getFitness(); + if(currentFitness >= requiredFitness) { + newPopulation[i] = candidate; + break; + } } - newPopulation[i] = new Candidate(population[j].getFolding()); } return newPopulation;