-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDna.js
More file actions
54 lines (44 loc) · 1.3 KB
/
Dna.js
File metadata and controls
54 lines (44 loc) · 1.3 KB
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
function newChar() {
var text = "";
var possible = " 1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.,;:'\"?{}[]\\/|!@#$%^&*()_+-=~`";
text = possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
class Dna{
constructor(num){
this.genes = [];
this.fitness = 0;
for (let i=0; i<num; i++){
this.genes[i]=newChar();
}
}
getPhrase(){
return this.genes.join("");
}
calcFitness(target){
let score = 0;
for (let i=0; i<this.genes.length; i++){
if(this.genes[i] == target.charAt(i)){
score++;
}
}
this.fitness= score / target.length;
// console.log("this.fitness = "+this.fitness);
}
crossover(partner){
let child = new Dna(this.genes.length);
let midpoint = floor(random(this.genes.length));
for(let i=0; i<this.genes.length; i++){
if(i > midpoint) child.genes[i] = this.genes[i];
else child.genes[i] = partner.genes[i];
}
return child;
}
mutate(mutationRate){
for(let i=0; i<this.genes.length; i++){
if (random(1) < mutationRate){
this.genes[i] = newChar();
}
}
}
}