1 10 package org.jgap.impl; 11 12 import java.util.*; 13 import org.jgap.*; 14 import org.jgap.distr.*; 15 16 25 public class FittestPopulationMerger 26 implements IPopulationMerger { 27 28 private final static String CVS_REVISION = "$Revision: 1.16 $"; 29 30 public Population mergePopulations(final Population a_population1, 31 final Population a_population2, 32 final int a_new_population_size) { 33 35 try { 36 a_population1.addChromosomes(a_population2); 38 List allChromosomes = a_population1.getChromosomes(); 41 Collections.sort(allChromosomes, new FitnessChromosomeComparator( 42 a_population1.getConfiguration())); 43 Chromosome[] chromosomes = (Chromosome[]) allChromosomes.toArray(new 46 Chromosome[0]); 47 Population mergedPopulation = new Population(a_population1. 48 getConfiguration(), a_new_population_size); 49 for (int i = 0; i < a_new_population_size && i < chromosomes.length; i++) { 50 mergedPopulation.addChromosome(chromosomes[i]); 51 } 52 return mergedPopulation; 55 } catch (InvalidConfigurationException iex) { 56 throw new IllegalStateException (iex.getMessage()); 58 } 59 } 60 61 70 private class FitnessChromosomeComparator 71 implements Comparator { 72 private transient Configuration m_config; 73 74 private FitnessEvaluator m_fEvaluator; 77 78 public FitnessChromosomeComparator(Configuration a_config) { 79 m_config = a_config; 80 m_fEvaluator = m_config.getFitnessEvaluator(); 81 } 82 83 93 public int compare(final Object a_o1, final Object a_o2) { 94 IChromosome chr1 = (IChromosome) a_o1; 96 IChromosome chr2 = (IChromosome) a_o2; 97 if (m_fEvaluator.isFitter(chr2.getFitnessValue(), 99 chr1.getFitnessValue())) { 100 return 1; 101 } 102 else if (m_fEvaluator.isFitter(chr1.getFitnessValue(), 103 chr2.getFitnessValue())) { 104 return -1; 105 } 106 else { 107 return 0; 108 } 109 } 110 } 111 } 112 | Popular Tags |