-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPopulation.pde
99 lines (82 loc) · 2.23 KB
/
Population.pde
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
public class Population {
Sequencer[] pop;
float fitnessSum, minFit = 1000;
int bestSeqInd = 0, gen = 1;
public Population(int size) {
pop = new Sequencer[size];
for (int i = 0; i < pop.length; i++) {
pop[i] = new Sequencer();
}
}
// has the phrase been found by any of the population?
public boolean hasFound() {
selectBest();
if (pop[bestSeqInd].brain.guessPhrase.equals(target)) {
showBest();
return true;
} else
return false;
}
public void naturalSelection() {
Sequencer[] newGen = new Sequencer[pop.length];
calculateFitnessSum();
selectBest();
newGen[0] = pop[bestSeqInd].getBaby(selectParent());
for (int i = 0; i < newGen.length; i++) {
Sequencer parentA = selectParent();
Sequencer parentB = selectParent();
newGen[i] = parentA.getBaby(parentB);
}
pop = newGen.clone();
gen++;
}
public void calculateFitness() {
for (Sequencer s : pop) {
s.calculateFitness();
}
}
public void calculateFitnessSum() {
fitnessSum = 0;
for (Sequencer s : pop) {
fitnessSum += s.fitness;
}
}
//selects best parent for natural selection (better fitness = better chance)
public Sequencer selectParent() {
float running = 0.0;
float rand = random(fitnessSum);
for (Sequencer s : pop) {
running += s.fitness;
if (rand < running) {
return s;
}
}
return null;
}
public void mutate() {
for (int i = 1; i < pop.length; i++) {
pop[i].brain.mutate();
}
}
//selects the most accurate phrase
public void selectBest() {
float maxFit = 0.0;
int maxI = 0;
for (int i = 0; i < pop.length; i++) {
if (pop[i].fitness > maxFit) {
maxFit = pop[i].fitness;
maxI = i;
}
//don't take a step backward, so automatically mutate
if (pop[i].fitness < minFit) {
pop[i].brain.mutate();
}
}
bestSeqInd = maxI;
minFit = pop[bestSeqInd].fitness;
}
//only shows user the best one
public void showBest() {
pop[bestSeqInd].showGuess();
}
}