Skip to content

Instantly share code, notes, and snippets.

@MatthiasKrijgsman
Created January 11, 2016 07:48
Show Gist options
  • Save MatthiasKrijgsman/6b52cce5d79dea0d3c8b to your computer and use it in GitHub Desktop.
Save MatthiasKrijgsman/6b52cce5d79dea0d3c8b to your computer and use it in GitHub Desktop.
Simple but powerful Genetic Algorithm
/**
* Author: Matthias Krijgsman
*
* Genetic Operator: One-point crossover
*
* Options input json:
* size - Population Size
* elimination - Elimination Rate
* mutation - Mutation Rate
* geneSize - DNA Size
*
* Methods:
* generate() - Generates a random list of dna
* next(x) - Takes x to the next generation
*
* x input:
* json array
*
* [
* {
* id: 0,
* score: 0,
* dna: "01001010"
* },
* {
* id: 1,
* score: 0,
* dna: "01001010"
* }
* ]
*
**/
var genetic;
String.prototype.setCharAt = function(index,chr) {
if(index > this.length-1) return str;
return this.substr(0,index) + chr + this.substr(index+1);
};
genetic = function(options){
this.s = options.size;
this.e = options.elimination;
this.m = options.mutation;
this.g = options.geneSize;
};
genetic.prototype.generate = function(){
var result = [];
for(var i = 0; i < this.s; i++){
var dna = "";
for(var n = 0; n < this.g; n++){
dna += Math.round(Math.random());
}
result.push(dna);
}
return result;
};
genetic.prototype.next = function(data){
data.sort(function(a,b){return b.score - a.score});
var i = Math.round(this.s*this.e);
if(i%2){i--}
var p = this.choose(i);
var d = [];
for(var i in p){
var p1 = p[i][0];
var p2 = p[i][1];
var r = this.operator(data[p1].dna, data[p2].dna);
d.push(r[0]);
d.push(r[1]);
}
for(var i in d){
data[((this.s-1)-i)].dna = d[i];
}
data.sort(function(a,b){return a.id - b.id});
for(var i in data){
if(Math.random() < this.m){
var x = Math.floor(Math.random() * this.g);
if(data[i].dna[x] == "0"){
data[i].dna = data[i].dna.setCharAt(x, "1");
}else{
data[i].dna = data[i].dna.setCharAt(x, "0");
}
}
}
return data;
};
genetic.prototype.choose = function(x){
var r = [];
var x2 = x/2;
while(x2--){
var p1 = Math.round(Math.random() * (this.s-x));
var p2 = Math.round(Math.random() * (this.s-x));
while(p1==p2){
p2 = Math.round(Math.random() * (this.s-x));
}
r.push([p1, p2]);
}
return r;
};
genetic.prototype.operator = function(a, b){
var c = Math.floor(Math.random() * this.g);
var x = a.slice(0, c) + b.slice(c, a.length);
var z = b.slice(0, c) + a.slice(c, a.length);
return [x, z];
};
var example = new genetic({
size: 100,
elimination: 0.4,
mutation: 0.01,
geneSize: 20
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment