-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathIndividual.java
114 lines (102 loc) · 2.69 KB
/
Individual.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package tsp;
public class Individual {
private int chromosome[];
private double fitness = -1;
/**
* Initializes individual with specific chromosome
*
* @param chromosome The chromosome to give individual
*/
public Individual(int chromosome[]){
// Create individual chromosome
this.chromosome = chromosome;
}
/**
* Initializes random individual
*
* @param chromosomeLength The length of the individuals chromosome
*/
public Individual(int chromosomeLength){
// Create random individual
int chromosome[] = new int[chromosomeLength];
for (int gene = 0; gene < chromosomeLength; gene++) {
chromosome[gene] = gene;
}
for (int geneIndex=0; geneIndex < chromosomeLength; geneIndex++) {
// Shuffle genes
int newGeneIndex = (int) (Math.random() * chromosomeLength);
// Swap individuals
int tempIndividual = chromosome[newGeneIndex];
chromosome[newGeneIndex] = chromosome[geneIndex];
chromosome[geneIndex] = tempIndividual;
}
this.chromosome = chromosome;
}
/**
* Gets individual's chromosome
*
* @return The individual's chromosome
*/
public int[] getChromosome(){
return this.chromosome;
}
/**
* Gets individual's chromosome length
*
* @return The individual's chromosome length
*/
public int getChromosomeLength(){
return this.chromosome.length;
}
/**
* Check if gene is contained in this individual
*
* @param gene Gene to look for
* @return boolean
*/
public boolean containsGene(int gene){
// Loop over genes
for (int i=0; i < this.getChromosomeLength(); i++) {
// Check for gene
if (this.getGene(i) == gene) {
return true;
}
}
return false;
}
/**
* Set gene at offset
*
* @param gene
* @param offset
* @return gene
*/
public void setGene(int gene, int offset){
this.chromosome[offset] = gene;
}
/**
* Get gene at offset
*
* @param offset
* @return gene
*/
public int getGene(int offset){
return this.chromosome[offset];
}
/**
* Store individual's fitness
*
* @param fitness The individuals fitness
*/
public void setFitness(double fitness){
this.fitness = fitness;
}
/**
* Gets individual's fitness
*
* @return The individual's fitness
*/
public double getFitness(){
return this.fitness;
}
}