01 /*
02 * CISELab, Computational and Intelligent Systems Engineering Laboratory
03 * Department of Engineering
04 * University of Sannio, 82100 Benevento (ITALY)
05 * web-site: www.ciselab.org
06 *
07 * JENES, A Java Library for Genetic Algorithms
08 * Copyright (C) 2009, Luigi Troiano
09 *
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
14 *
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
23 02110-1301 USA
24 *
25 * COPYRIGHT DISCLAIMER
26 * CISELab, hereby disclaims all copyright interest in the
27 * library `JENES' (A Java Library for Genetic Algorithms)
28 * written by Luigi Troiano et al.
29 *
30 * Luigi Troiano, 1 January 2009
31 * CISELab Coordinator
32 */
33 package jenes.tutorials.problem3;
34
35 import jenes.GeneticAlgorithm;
36 import jenes.Random;
37 import jenes.chromosome.IntegerChromosome;
38 import jenes.population.Individual;
39 import jenes.population.Population;
40
41 public class TSPGA extends GeneticAlgorithm<IntegerChromosome> {
42
43 private double[][] matrix;
44
45 public TSPGA(double[][] matrix, Population<IntegerChromosome> pop, int genlimit) {
46 super(pop, genlimit);
47 this.matrix = matrix;
48 }
49
50 @Override
51 protected void evaluateIndividual(Individual<IntegerChromosome> individual) {
52 IntegerChromosome chrom=individual.getChromosome();
53 double count = 0;
54 int size = chrom.length();
55 for(int i=0;i<size-1;i++){
56 int val1 = chrom.getValue(i);
57 int val2 = chrom.getValue(i+1);
58 count += matrix[val1][val2];
59 }
60 count += matrix[size-1][0];
61
62 individual.setScore(count);
63 }
64
65 @Override
66 protected void randomizeIndividual(Individual<IntegerChromosome> individual) {
67 Random rand = Random.getInstance();
68 int len = individual.getChromosomeLength();
69 for( int i = 0; i < 100; ++i ) {
70 int j = rand.nextInt(len);
71 int k = rand.nextInt(len);
72 individual.getChromosome().swap(j, k);
73 }
74 }
75
76 }
|
|
|