Tuesday, December 14, 2010

Evolving "Hello World!"

puremango has put together a nice little writeup on using genetic algorithms to generate the classic "Hello World!" He has an attached webpage that lets you play with the parameters and generate a nice graph.

A few years ago I put together a generic genetic javascript algorithm webpage. While it doesn't have the nice writeup or the cool graph (only a basic one) the cool feature was that you could modify the input box to put in your problem. Taking a few minutes here is the hello world! version that you can put in the text box and run to have it discover hello world.


function salesman() {
this.target = "hello world!";

this.fitness = function(chromosome) {
var f = 0; // start at 0; the best fitness
for(var i=0, c=this.target.length; i f -= Math.abs(this.target.charCodeAt(i) - chromosome[i]);
}
return Math.abs(f);
};

// the size of values that should be passed to fitness
this.numberOfArgs = function() { return this.target.length; };

// the max value needed for the arguments
this.maxArg = function() { return 128 }; // ascii

// convert the current chromosome value which can have a maxValue
// into something fitness can use.
this.getArg = function(value, maxValue) {
return value;
};

// Paint the solution onto bestimage
this.paint = function(values) {
var canvas = document.getElementById('bestimage');
if (canvas.getContext){
var canvasContext = canvas.getContext('2d');
canvasContext.clearRect(0, 0, canvas.width, canvas.height);

canvasContext.font = "italic 200 12px/2 Unknown Font, sans-serif";
canvasContext.strokeStyle = "blue";
for (var i = 0; i < values.length; ++i){
canvasContext.strokeText(String.fromCharCode(values[i]), i*10, 10);
}
}
}
} salesman;

No comments:

Popular Posts