1 10 package examples.salesman; 11 12 import org.jgap.*; 13 import org.jgap.impl.*; 14 import org.jgap.impl.salesman.*; 15 16 57 public class TravellingSalesman 58 extends Salesman { 59 60 private static final String CVS_REVISION = "$Revision: 1.12 $"; 61 62 63 public static final int CITIES = 7; 64 65 75 public IChromosome createSampleChromosome(Object a_initial_data) { 76 try { 77 Gene[] genes = new Gene[CITIES]; 78 for (int i = 0; i < genes.length; i++) { 79 genes[i] = new IntegerGene(getConfiguration(), 0, CITIES - 1); 80 genes[i].setAllele(new Integer (i)); 81 } 82 IChromosome sample = new Chromosome(getConfiguration(), genes); 83 System.out.println("Optimal way " + sample); 84 System.out.println("Score " + 85 (Integer.MAX_VALUE / 2 - 86 getConfiguration().getFitnessFunction() 87 .getFitnessValue(sample))); 88 shuffle(genes); 89 System.out.println("Sample chromosome " + sample); 90 System.out.println("Score " + 91 (Integer.MAX_VALUE / 2 - 92 getConfiguration().getFitnessFunction() 93 .getFitnessValue(sample))); 94 return sample; 95 } 96 catch (InvalidConfigurationException iex) { 97 throw new IllegalStateException (iex.getMessage()); 98 } 99 } 100 101 113 public double distance(Gene a_from, Gene a_to) { 114 IntegerGene a = (IntegerGene) a_from; 115 IntegerGene b = (IntegerGene) a_to; 116 int A = a.intValue(); 117 int B = b.intValue(); 118 if (A == 0 && B == CITIES - 1) { 119 return 1; 120 } 121 if (B == 0 && A == CITIES - 1) { 122 return 1; 123 } 124 return Math.abs(A - B); 125 } 126 127 137 public static void main(String [] args) { 138 try { 139 TravellingSalesman t = new TravellingSalesman(); 140 IChromosome optimal = t.findOptimalPath(null); 141 System.out.println("Solution: "); 142 System.out.println(optimal); 143 System.out.println("Score " + 144 (Integer.MAX_VALUE / 2 - optimal.getFitnessValue())); 145 } 146 catch (Exception ex) { 147 ex.printStackTrace(); 148 } 149 } 150 } 151 | Popular Tags |