A simpler C# genetic algorithm






4.58/5 (10 votes)
Feb 27, 2005
2 min read

93831

15665
A simple demonstration of an algorithm making good use of C# 2.0
Introduction
This article deals with enhancements for the Simple C# Genetic Algorithm by Barry Lapthorn. It makes an extensive use of "foreach" loop and .NET2.0 C# language improvements, so the .NET 2.0 framework or higher is needed.
The program does the same thing and gives the same results as Barry's one.
My Modifications :
- use of generic List.
Allows the use of type safe Collections.
- use of the 'foreach' statement whenever possible.
It exists since .NET 1.0
- use of a deep copy of a 'Genome' object for 'elitism'
Here I needed a copy of a Genome object to cope with elitism (a concept of Genetic Programming). I didn't find anything useful in the .NET 2.0 framework so I coded my own method ofGenome.DeepCopy
which performs a full-blown copy of aGenome
object. i.e. it returns a newGenome
object whose fields are the exact reproduction of the original, but the twoGenome
objects don't share any fields or value in common (in the sense that duplication of a Genome IS NOT a pointer to a former object).
- use of delegate for the sort (no more need of a 'GenomeComparer' class)
m_thisGeneration.Sort(delegate(Genome x, Genome y) { return Comparer<DOUBLE>.Default.Compare(x.Fitness, y.Fitness); });
To my mind, this is the most powerfull enhancement. Here the code uses an anonymous function (with thedelegate
keyword) to perform the sort. This makes the code much shorter and clearer and avoids using aGenomeComparer
helper class.
Improvements that can be done
The scaling of the GA parameters, ie allowing other mathematical functions to work with the GA (Genetic Algorithm) not only those with values between 0 and 1 (double floating point precision).
For example :
double f3 = (x * x * x + y * y * y + 3 * x * y);
I encourage you to follow this link to Barry Lapthorn's site : http://www.lapthorn.net/
I made this to learn visual c# express 2005. I hope someone will find some elements interresting in my work. Nevertheless, I don't pretend to be a top-level OO Programmer :-)