01 /*
02 * JENES
03 * A time asnd memory efficient Java library for genetic algorithms and more
04 * Copyright (C) 2011 Intelligentia srl
05 *
06 * This program is free software: you can redistribute it and/or modify
07 * it under the terms of the GNU General Public License as published by
08 * the Free Software Foundation, either version 3 of the License, or
09 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19 package jenes.tutorials.old.problem3;
20
21 import jenes.GeneticAlgorithm;
22 import jenes.utils.Random;
23 import jenes.chromosome.IntegerChromosome;
24 import jenes.population.Individual;
25 import jenes.population.Population;
26
27 /**
28 * Tutorial showing how to implement problem specific operators.
29 * The problem faced in this example is the well known Tavel Salesman Problem (TSP)
30 *
31 * This class implements the algorithm.
32 *
33 * @author Luigi Troiano
34 * @author Pierpaolo Lombardi
35 *
36 * @version 1.0
37 * @since 1.0
38 */
39 public class TSPGA extends GeneticAlgorithm<IntegerChromosome> {
40
41 private double[][] matrix;
42
43 public TSPGA(double[][] matrix, Population<IntegerChromosome> pop, int genlimit) {
44 super(pop, genlimit);
45 this.matrix = matrix;
46 }
47
48 @Override
49 public void evaluateIndividual(Individual<IntegerChromosome> individual) {
50 IntegerChromosome chrom=individual.getChromosome();
51 double count = 0;
52 int size = chrom.length();
53 for(int i=0;i<size-1;i++){
54 int val1 = chrom.getValue(i);
55 int val2 = chrom.getValue(i+1);
56 count += matrix[val1][val2];
57 }
58 count += matrix[size-1][0];
59
60 individual.setScore(count);
61 }
62
63 @Override
64 protected void randomizeIndividual(Individual<IntegerChromosome> individual) {
65 Random rand = Random.getInstance();
66 int len = individual.getChromosomeLength();
67 for( int i = 0; i < 100; ++i ) {
68 int j = rand.nextInt(len);
69 int k = rand.nextInt(len);
70 individual.getChromosome().swap(j, k);
71 }
72 }
73
74 }
|
|
|