-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathIndividual.java
More file actions
72 lines (62 loc) · 1.83 KB
/
Copy pathIndividual.java
File metadata and controls
72 lines (62 loc) · 1.83 KB
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
public class Individual {
static int defaultGeneLength = 64;
private byte[] genes;
// Cache
private int fitness = 0;
// Create a random individual
public Individual() {
genes = new byte[defaultGeneLength];
for (int i = 0; i < size(); i++) {
byte gene = (byte) Math.round(Math.random());
genes[i] = gene;
}
}
// Create a local individual
public Individual(String chromosome) {
defaultGeneLength = chromosome.length();
genes = new byte[defaultGeneLength];
for (int i = 0; i < chromosome.length(); i++) {
byte gene = Byte.parseByte(Character.toString(chromosome.charAt(i)));
genes[i] = gene;
}
}
// Create a local individual
public Individual(int chromosomeSize) {
defaultGeneLength = chromosomeSize;
genes = new byte[defaultGeneLength];
for (int i = 0; i < size(); i++) {
byte gene = (byte) Math.round(Math.random());
genes[i] = gene;
}
}
/* Getters and setters */
// Use this if you want to create individuals with different gene lengths
public static void setDefaultGeneLength(int length) {
defaultGeneLength = length;
}
public byte getGene(int index) {
return genes[index];
}
public void setGene(int index, byte value) {
genes[index] = value;
fitness = 0;
}
/* Public methods */
public int size() {
return genes.length;
}
public int getFitness() {
if (fitness == 0) {
fitness = Hash.getFitness(this);
}
return fitness;
}
@Override
public String toString() {
String geneString = "";
for (int i = 0; i < size(); i++) {
geneString += getGene(i);
}
return geneString;
}
}