- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGA.java
More file actions
Latest commit
110 lines (91 loc) · 2.56 KB
/
Copy pathGA.java
File metadata and controls
110 lines (91 loc) · 2.56 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
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
importjava.util.*;
/**
* Generic genetic algorithm.
*/
publicclassGA<TextendsGene> {
protectedList<T> list;
protectedintgenerationSize; // typically 50 - 100
protectedintnbrGenerations;
protectedClass<T> clazz; // to be able to crete new T instances
publicGA(intgenerationSize, intnbrGenerations, Class<T> clazz) {
this.generationSize = generationSize;
this.nbrGenerations = nbrGenerations;
this.clazz = clazz;
/* Represent the problem as binary vector, integer vector or
real value genes. */
list = newLinkedList<T>();
run();
}
voidrun(){
/* Randomize the first generation of genes */
for (intk = 0; k < generationSize; k++) {
Tgene = newT();
gene.setRandomValue();
list.add(gene);
}
for (intk = 0; k < nbrGenerations; k++) {
/* Calculate fitness for each gene according
to a pre-determined function */
for (inti = 0; i < generationSize; i++) {
list.get(i).setFitness();
}
/* Sort the genes in the list according to fitness,
best on top */
sort();
for(inti = 0; i < generationSize; i+= 2){
/* Mating/cross over: recombine the genes two by two */
Tgene1 = list.get(i);
Tgene2 = list.get(i+1);
Toffspring = newT();
offspring.setValue(gene1.combineValues(gene2.getValue()));
/* Calculate fitness for the offspring and put it
on the right place in the list. */
offspring.setFitness();
place(offspring);
}
/* Throw away the worst 1/3 genes to maintain
the generation size */
LinkedList<T> tmp = newLinkedList<T>();
for (inti = 0; i < generationSize; i++) {
tmp.add(list.get(i));
}
list = tmp;
/* Mutation, often the best values (e.g. the top 20%)
is held mutation free */
for (inti = generationSize/5; i < generationSize; i++) {
Tgene = list.get(i);
gene.setValue(gene.mutateValue());
}
}
/* Print the top 3 results. */
for (inti = 0; i < 3; i++) {
System.out.println(list.get(i).getValue());
}
}
/* Sort according to fitness. */
privatevoidsort(){
List<T> tmp = list;
list = newArrayList<T>();
for(Tg : tmp){
place(g);
}
}
/* Insert a gene on the correct place in a list. */
privatevoidplace(Tgene){
for (intk = 0; k < list.size(); k++) {
if (list.get(k).getFitness() > gene.getFitness()) {
list.add(k, gene);
return;
}
}
list.add(list.size(), gene);
}
/* In order to create new instances of T */
privateTnewT() {
try{
returnclazz.newInstance();
}catch(Exceptione){
returnnull;
}
}
}