GenAlgo
by g30rg3
HTML
<textarea id="pattern"></textarea>
CSS
textarea {
width:100%;
}
JavaScript
var population = [];
var Chromosome = function (target, sequence) {
this.mutationRate = 0.0001,
this.crossoverRate = 0.7,
this.chromoLength = 5;
this.target = target;
this.initChars();
if (sequence) {
this.sequence = sequence;
} else {
this.initSequence();
}
};
Chromosome.prototype.initSequence = function () {
var allArray = $.map(this.all, function (v, k) {
return v;
}),
j, r;
this.sequence = '';
for (j = 0; j < this.chromoLength; j++) {
r = Math.floor(Math.random() * (allArray.length));
this.sequence += allArray[r];
}
};
Chromosome.prototype.initChars = function () {
this.chars = {
'0': '0000',
'1': '0001',
'2': '0010',
'3': '0011',
'4': '0100',
'5': '0101',
'6': '0110',
'7': '0111',
'8': '1000',
'9': '1001'
};
this.ops = {
'+': '1010',
'-': '1011',
'*': '1100',
'/': '1101'
};
this.all = $.extend({}, this.chars, this.ops);
this.invertedAll = {};
var that = this;
$.map(this.all, function (v, k) {
that.invertedAll['' + v] = k;
});
};
Chromosome.prototype.computeFitness = function () {
var item = this.compute(),
fitness;
if(item && !item == Infinity){
fitness = null;
}else{
fitness = 1 / Math.abs((this.target - item));
}
//console.log(fitness);
return fitness;
};
Chromosome.prototype.compute = function () {
var that = this,
genes = this.decode(),
previousWasOps = false,
thisIsOps = false,
tempGenes = [],
total;
$.each(genes, function (i, e) {
thisIsOps = that.ops.hasOwnProperty(e);
if (!(thisIsOps && previousWasOps)) {
tempGenes.push(e);
}
previousWasOps = thisIsOps;
});
try {
total =...