-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPopulation.js
63 lines (54 loc) · 1.47 KB
/
Population.js
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
// José Bezerra - 21/07/2018
function Population() {
this.rockets = [];
this.maxPop = maxPop;
for (var i = 0; i < this.maxPop; i++) {
this.rockets[i] = new Rocket();
}
this.maxFitness = 0;
this.generations = 0;
this.inTarget = 0;
this.averageFitness = 0;
}
Population.prototype.show = function () {
for (var i = 0; i < this.rockets.length; i++) {
this.rockets[i].update();
this.rockets[i].show();
}
}
Population.prototype.calcFitness = function () {
var maxFit = 0;
this.inTarget = 0;
for (var i = 0; i < this.rockets.length; i++) {
this.rockets[i].calDist();
if (maxFit < this.rockets[i].fitness) {
maxFit = this.rockets[i].fitness;
}
//check completed rockets
if(this.rockets[i].completed){
this.inTarget++;
}
}
this.maxFitness = maxFit;
}
Population.prototype.acceptReject = function () {
while (true) {
var n = random(this.maxFitness);
var randomElem = random(this.rockets);
if (n < randomElem.fitness) {
return randomElem;
}
}
}
Population.prototype.naturalSelection = function () {
var newpop = [];
for (var i = 0; i < this.maxPop; i++) {
var a = this.acceptReject();
var b = this.acceptReject();
var child = a.crossover(b);
newpop.push(child);
}
this.rockets = newpop;
this.generations++;
}