-
Notifications
You must be signed in to change notification settings - Fork 2
/
Genome.js
110 lines (71 loc) · 1.9 KB
/
Genome.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
function Genome(genomeJSON){
/* Setup Genome using configuration object */
this.potentialGenes = JSON.parse(genomeJSON);
this.names = Object.keys(this.potentialGenes);
this.count = Object.keys(this.potentialGenes).length;
this.genes = new Array();
/* Methods for initialization */
// NOTE: This distribution may not be completely random.
this.getRandomGene = function(name){
var values = this.potentialGenes[name];
return values[Math.floor(Math.random()*values.length)];;
}
this.setRandomGene = function(name){
this.genes[name] = this.getRandomGene(name);
}
this.setRandomGenes = function(){
for (var i = 0; i < this.count; i++){
this.setRandomGene(this.names[i]);
}
}
// Initialize Genes
this.setRandomGenes();
/* More Getters and Setters */
this.getGenes = function(){
return this.genes;
}
this.getNames = function(){
return this.names;
}
this.getCount = function(){
return this.count;
}
/* Genetic operators */
this.mutate = function(chance){
for (var i = 0; i < this.count; i++){
if(Math.random() <= chance){
var name = this.names[i];
this.setRandomGene(name);
}
}
}
/* Helper Methods */
this.hasGene = function(nameToMatch, valueToMatch){
if(this.names.indexOf(nameToMatch) > -1){
if(valueToMatch == this.genes[nameToMatch]){
return true;
}
}
return false;
}
this.isEqual = function(genomeToMatch){
var namesToMatch = genomeToMatch.getNames();
var genesToMatch = genomeToMatch.getGenes();
for (var i = 0; i < genomeToMatch.getCount(); i++){
var nameToMatch = namesToMatch[i];
var valueToMatch = genesToMatch[nameToMatch];
if(!this.hasGene(nameToMatch, valueToMatch)){
return false;
}
}
return true;
}
// Prints
this.printGenome = function(){
genes = this.genes
Object.keys(genes).forEach(function (key) {
console.log(key + ": " + genes[key]);
});
}
}
module.exports = Genome;