function Cat(name) {
this.name = name;
this.callMe = function() {
alert("Here " + this.name + "!");
};
}
var kitty = new Cat("kitty");
kitty.callMe();
function Cat(name) {
this.name = name;
};
Cat.prototype = {
callMe : function() {
alert("Here " + this.name + "!");
}
};
var animals = animals || {};
animals.Cat = function(name) { ... };
animals.Cat.prototype = { ... };
var kitty = new animals.Cat("kitty");
kitty.callMe();
javascript String object
javascript Math object
Implement following utility functions in file genetic/utils.js
genetic.Utils.randomString(length) – generates random string of given length
var s = genetic.Utils.randomString(10);
console.log("s:'" + s + "', s.length:" + s.length);
s:'g(ay+9a;3', s.length:10
genetic.Utils.distance(str1, str2) – squared euclidean distance of two same length strings
console.log(genetic.Utils.distance("1234", "1235"));
console.log(genetic.Utils.distance("1230", "1235"));
1
25
Implement Gene object in genetic/gene.js
var alpha = new genetic.Gene("alpha");
var betaa = new genetic.Gene("betaa");
cost – calculates the cost of this gene from given value
console.log("cost: " + alpha.cost("alphc"));
cost: 4
mutate – randomly modifies a single character in this genes value
alpha.mutate();
console.log("mutate: " + alpha.value);
mutate: aloha
mate – combine gene with given gene to produce two new genes
var nextGen = alpha.mate(betaa);
console.log("nextGen: '" + nextGen[0].value + "' , '" + nextGen[1].value);
nextGen: 'altaa' , 'beoha
Implement Population object in genetic/population.js.
Constructor takes the goal string and population size and generates a pool of randomly generated Genes
var population = new genetic.Population("Hello World!", 10);
The sortGenes orders the genes in the pool based on their cost (distance from goal)
population.sortGenes();
The tryMutate mutates each gene in the pool with 50% probability
population.tryMutate();
The eliminateLastTwo removes the two poorest genes from the pool
population.eliminateLastTwo();
The mateFirstTwo mates the two best genes and pushes their children at the end of the pool
population.mateFirstTwo();
Implement the genetic algorithm in Population objects generation function:
- Mutate genes in the pool
- Sort genes
- Kill poorest
- Mate best
var population = new genetic.Population("Hello world!", 10);
var result = population.generation();
console.log("Result: " + result.generation + " '" + result.value + "' " + result.cost);
var result2 = population.generation();
console.log("Result: " + result2.generation + " '" + result2.value + "' " + result2.cost);
Result: 1 '1j/Ä,Kwr23Rt' 57474
Result: 2 '2j/Ä,xx^SaMt' 53838
http://burakkanber.com/blog/machine-learning-genetic-algorithms-part-1-javascript/
http://addyosmani.com/resources/essentialjsdesignpatterns/book/
http://jstherightway.com/