package algorithms.geneticAlgorithm.Components.Selections; import java.util.ArrayList; import java.util.Collections; import java.util.Random; import algorithms.geneticAlgorithm.Components.GAIndividual; import algorithms.geneticAlgorithm.Components.GASelectionStrategy; public class TournamentRankSelection implements GASelectionStrategy{ public class Range{ public double min; public double max; public Range(double min, double max){ this.min = min; this.max = max; } } private ArrayList currentPop; public int tournamentSize; private Random rng; private ArrayList tournamentWheel; public ArrayList competitors; //public double selectProb; private double maxRange; public TournamentRankSelection(){ currentPop = new ArrayList(); tournamentSize = 1; rng = new Random(); } public TournamentRankSelection(int tSize){ currentPop = new ArrayList(); rng = new Random(); tournamentSize = tSize; } @Override public void setCurrentPopulation(ArrayList population) { currentPop.clear(); currentPop.addAll(population); } public void setTournamentSize(int size){ tournamentSize = size; } @Override public ArrayList selectIndividuals() { ArrayList parents = new ArrayList(); parents.add(selectSingleIndividual()); parents.add(selectSingleIndividual()); return parents; } public I selectSingleIndividual(){ tournamentSelection(); initWheel(); double index = rng.nextDouble() * maxRange; for(int i = 0; i < tournamentWheel.size(); i++){ if(index >= tournamentWheel.get(i).min && index <= tournamentWheel.get(i).max){ return competitors.get(i); } } return competitors.get(rng.nextInt(competitors.size())); } public void tournamentSelection(){ competitors = new ArrayList(); Collections.shuffle(currentPop); for(int i = 0; i < tournamentSize; i++){ //I candidate = chooseCandidate(); I candidate = currentPop.get(i); int size = competitors.size(); for(int j = 0; j <= size; j++){ if(j != size){ if(competitors.get(j).getFittness() < candidate.getFittness()){ competitors.add(j, candidate); break; } }else{ competitors.add(candidate); } } } } public I chooseCandidate(){ int index = rng.nextInt(currentPop.size()); I candidate = currentPop.get(index); return candidate; } public void initWheel(){ tournamentWheel = new ArrayList(); int power = 0; maxRange = 0; for(int i = 0; i < tournamentSize; i++){ Range range = new Range(maxRange, maxRange + tournamentSize - i); tournamentWheel.add(range); maxRange += tournamentSize - i; /* double currentProb = selectProb * Math.pow((1- selectProb), power); Range range = new Range(maxRange, maxRange + currentProb); tournamentWheel.add(range); maxRange += currentProb; power++; */ } } }