-
Notifications
You must be signed in to change notification settings - Fork 0
/
dna.js
41 lines (35 loc) · 1.02 KB
/
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
37
38
39
40
41
// Daniel Shiffman
// https://www.kadenze.com/courses/the-nature-of-code
// http://natureofcode.com/
// Session 5: Evolutionary Computing
// Class to describe DNA
// Has more features for two parent mating (not used in this example)
// Constructor (makes a random DNA)
function DNA(newgenes) {
if (newgenes) {
this.genes = newgenes;
} else {
// The genetic sequence
// DNA is random floating point values between 0 and 1 (!!)
this.genes = new Array(1);
for (var i = 0; i < this.genes.length; i++) {
this.genes[i] = random(0,1);
}
}
this.copy = function() {
// should switch to fancy JS array copy
var newgenes = [];
for (var i = 0; i < this.genes.length; i++) {
newgenes[i] = this.genes[i];
}
return new DNA(newgenes);
}
// Based on a mutation probability, picks a new random character in array spots
this.mutate = function(m) {
for (var i = 0; i < this.genes.length; i++) {
if (random(1) < m) {
this.genes[i] = random(0,1);
}
}
}
}