Recently I spent time playing with generic algorithms. I was looking for something easy enough to implement (read: PLAIN LAZY) and I found the Hello World! (literally) of genetic algorithms.
Gathering the algorithm itself from the C++ example (in the link above), I re-designed and re-coded the whole thing in C#.
TypingMonkey is a very simple application which uses a number (defined by the user) of random strings to evolve the user input text.
From the screen-shot below you can see how it took the algorithm 87 generations to evolve the string ".NET Butchering" from an initial population of 2500 random 15-characters strings:
Why "typing monkey"? Inspired by the Infinite Monkey Theorem, I am pretending our population of random string is generated by a typing monkey:
/// The Typing monkey generates random strings - can't be static 'cause it's a monkey.
/// If you wait long enough it will eventually produce Shakespeare.
class TypingMonkey
{
private const string legalCharacters = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.";
static Random random = new Random();
/// The Typing Monkey Generates a random string with the given length.
public string TypeAway(int size)
{
StringBuilder builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = legalCharacters[random.Next(0, legalCharacters.Length)];
builder.Append(ch);
}
return builder.ToString();
}
}
You can find the source code here: http://github.com/JohnIdol/typingmonkey/tree/master
Feel free to contribute or despise.