Inspired by recent genetic algorithms floating around, I decided to try my hand at implementing one in perl. I’d thought for a long time that it would be quite difficult, but really it’s quite easy. My biggest hangup was dealing with data structures, but once I did that, it turns out that all you really need is a few functions:
- A fitness function, that determines which individuals are most fit to reproduce
- A mutate function, that will add random chance into each generation
- A breed function that allows the best individuals to reproduce.
I ended up implementing a very simple algorithm, but it’s fairly fast and very generic – it can be easily adapted to just about any task. Sadly, I have no fascinating application just yet, but if I stumble across one, I’ll be sure to post about it.
After the jump, I’ll put up some of the code I used and a link to the script, all for your viewing pleasure.