-
Notifications
You must be signed in to change notification settings - Fork 0
/
dna.js
36 lines (32 loc) · 903 Bytes
/
dna.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
class DNA {
constructor(genes) {
this.maxForce = 0.5;
this.genes = [];
if (arguments.length < 1) {
for (let i = 0; i < LIFETIME; i++) {
this.genes[i] = p5.Vector.random2D();
this.genes[i].mult(random(this.maxForce));
}
} else {
this.genes = genes;
}
}
crossover(partner) {
let childgenes = [];
let midpoint = floor(random(this.genes.length));
for (let i = 0; i < this.genes.length; i++) {
if (i > midpoint) childgenes[i] = this.genes[i];
else childgenes[i] = partner.genes[i];
}
let newchild = new DNA(childgenes);
return newchild;
}
mutate(mutationRate) {
for (let i = 0; i < this.genes.length; i++) {
if (random(1) < mutationRate) {
this.genes[i] = p5.Vector.random2D();
this.genes[i].mult(random(this.maxForce));
}
}
}
}