KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jgap > util > ChromosomeFitnessComparator


1 /*
2  * This file is part of JGAP.
3  *
4  * JGAP offers a dual license model containing the LGPL as well as the MPL.
5  *
6  * For licencing information please see the file license.txt included with JGAP
7  * or have a look at the top of class org.jgap.Chromosome which representatively
8  * includes the JGAP license policy applicable for any file delivered with JGAP.
9  */

10 package org.jgap.util;
11
12 import java.util.Comparator JavaDoc;
13 import org.jgap.*;
14
15 /**
16  * Simple comparator to allow the sorting of Chromosome lists with the highest
17  * fitness value in first place of the list.
18  * Usage example:
19  * Collections.sort(
20  * population.getChromosomes(), new ChromosomeFitnessComparator() );
21  *
22  * @author Charles Kevin Hill, Klaus Meffert
23  * @since 2.4
24  */

25 public class ChromosomeFitnessComparator
26     implements Comparator JavaDoc {
27   /** String containing the CVS revision. Read out via reflection!*/
28   private final static String JavaDoc CVS_REVISION = "$Revision: 1.8 $";
29
30   private FitnessEvaluator m_fitnessEvaluator;
31
32   /**
33    * Constructs the comparator using the DefaultFitnessEvaluator
34    *
35    * @author Klaus Meffert
36    * @since 2.6
37    */

38   public ChromosomeFitnessComparator() {
39     this(new DefaultFitnessEvaluator());
40   }
41
42   /**
43    * @param a_evaluator the fitness evaluator to use
44    *
45    * @author Klaus Meffert
46    * @since 2.6
47    */

48   public ChromosomeFitnessComparator(FitnessEvaluator a_evaluator) {
49     if (a_evaluator == null) {
50       throw new IllegalArgumentException JavaDoc("Evaluator must not be null");
51     }
52     m_fitnessEvaluator = a_evaluator;
53   }
54
55   /**
56    * Compares two chromosomes by using a FitnessEvaluator.
57    *
58    * @param a_chromosome1 the first chromosome to compare
59    * @param a_chromosome2 the second chromosome to compare
60    * @return -1 if a_chromosome1 is fitter than a_chromosome2, 1 if it is the
61    * other way round and 0 if both are equal
62    * @author Charles Kevin Hill, Klaus Meffert
63    * @since 2.6
64    */

65   public int compare(final Object JavaDoc a_chromosome1, final Object JavaDoc a_chromosome2) {
66     IChromosome chromosomeOne = (IChromosome) a_chromosome1;
67     IChromosome chromosomeTwo = (IChromosome) a_chromosome2;
68     if (m_fitnessEvaluator.isFitter(chromosomeOne, chromosomeTwo)) {
69       return -1;
70     }
71     else if (m_fitnessEvaluator.isFitter(chromosomeTwo, chromosomeOne)) {
72       return 1;
73     }
74     else {
75       return 0;
76     }
77   }
78 }
79
Popular Tags