KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jgap > impl > salesman > SalesmanFitnessFunction


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.impl.salesman;
11
12 import org.jgap.*;
13
14 /**
15  * The fitness function to solve the Travelling Salesman problem. The function
16  * returned by this method calls {@link org.jgap.impl.salesman.Salesman#distance
17  * distance(Object from, Object to) }
18  *
19  * @author Audrius Meskauskas
20  * @since 2.0
21  */

22 public class SalesmanFitnessFunction
23     extends FitnessFunction {
24   /** String containing the CVS revision. Read out via reflection!*/
25   private final static String JavaDoc CVS_REVISION = "$Revision: 1.9 $";
26
27   private final Salesman m_salesman;
28
29   public SalesmanFitnessFunction(final Salesman a_salesman) {
30     m_salesman = a_salesman;
31   }
32
33   /**
34    * Computes the distance by calling salesman
35    * {@link org.jgap.impl.salesman.Salesman#distance(org.jgap.Gene, org.jgap.Gene) }
36    *
37    * @param a_subject chromosome representing cities
38    * @return distance of the journey thru the cities represented in the
39    * given chromosome
40    *
41    * @author Audrius Meskauskas
42    * @since 2.0
43    */

44   protected double evaluate(final IChromosome a_subject) {
45     double s = 0;
46     Gene[] genes = a_subject.getGenes();
47     for (int i = 0; i < genes.length - 1; i++) {
48       s += m_salesman.distance(genes[i], genes[i + 1]);
49     }
50     // add cost of coming back:
51
s += m_salesman.distance(genes[genes.length - 1], genes[0]);
52     return Integer.MAX_VALUE / 2 - s;
53   }
54 }
55
Popular Tags