-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPopulation.pde
More file actions
107 lines (87 loc) · 2 KB
/
Population.pde
File metadata and controls
107 lines (87 loc) · 2 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
class Population {
Dot[] dots;
float fitnessSum;
int generation;
int bestDotIndex;
Population(int size, float mutationRate) {
dots = new Dot[size];
for (int i = 0; i < size; i++) {
dots[i] = new Dot(mutationRate);
}
generation = 1;
bestDotIndex = 0;
}
void show() {
for (int i = 0; i < dots.length; i++) {
dots[i].show();
}
}
void update() {
for (int i = 0; i < dots.length; i++) {
dots[i].update();
}
}
void calculateFitness() {
for (int i = 0; i < dots.length; i++) {
dots[i].calculateFitness();
}
}
boolean allDotsDead() {
for (int i = 0; i < dots.length; i++) {
if (!dots[i].dead && !dots[i].reachedGoal) {
return false;
}
}
numOnTarget = 0;
return true;
}
void naturalSelection() {
Dot[] newDots = new Dot[dots.length];
setBestDot();
calculateFitnessSum();
newDots[0] = dots[bestDotIndex].makeBaby();
newDots[0].isBest = true;
for (int i = 1; i < newDots.length; i++) {
// Select parent based on fitness
Dot parent = selectParent();
// Get babies from the parent
newDots[i] = parent.makeBaby();
}
dots = newDots.clone();
generation++;
}
void calculateFitnessSum() {
fitnessSum = 0;
for (int i = 0; i < dots.length; i++) {
fitnessSum += dots[i].fitness;
}
}
Dot selectParent() {
float rand = random(fitnessSum);
float runningSum = 0;
for (int i = 0; i < dots.length; i++) {
runningSum += dots[i].fitness;
if (runningSum > rand) {
return dots[i];
}
}
return null;
}
void mutateChildren() {
for (int i = 0; i < dots.length; i++) {
dots[i].brain.mutate();
}
}
void setBestDot() {
float max = 0;
int maxIndex = 0;
for (int i = 0; i < dots.length; i++) {
if (dots[i].fitness > max) {
max = dots[i].fitness;
maxIndex = i;
}
}
peakFitness = max;
bestDotIndex = maxIndex;
}
}