-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDNA.js
More file actions
43 lines (38 loc) · 807 Bytes
/
DNA.js
File metadata and controls
43 lines (38 loc) · 807 Bytes
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
function randf(lo, hi) {
return Math.random() * (hi + 1) + lo;
}
function randint(lo, hi) {
return Math.floor(randf(lo, hi));
}
class DNA {
constructor(len) {
this.dnaLength = len;
this.dna = [];
}
mutate(rate) {
for (let d in this.dna) {
if (randf(0, 1) < rate) {
//this.dna[d] += randf(-21, 21);
}
}
if (randf(0, 1) < rate){
this.dna[randint(0, this.dna.length-1)] += randf(-20, 10)
}
}
crossover(p){
let newDna = new DNA(this.dnaLength)
for (let i in p){
if (randf(0, 1) < 0.5){
newDna.dna.push(this.dna[i])
}else{
newDna.dna.push(p[i])
}
}
this.dna = [...newDna.dna]
}
initialize() {
for (let i = 0; i < this.dnaLength; i++) {
this.dna.push(randint(0, 255));
}
}
}