Genetic Algorithm Implementation in C# - YuryENG/Slab-Yard-Optimization GitHub Wiki
After reading a great article and watching tutorial videos about Genetic Algorithm by "The codding train" I decided to implement the code in C#, WPF.
The original article and video tutorials can be found here:
* 9.1: Genetic Algorithm: Introduction - The Nature of Code
https://www.youtube.com/watch?v=9zfeTw-uFCw&t=11s
* Chapter 9. The Evolution of Code
http://natureofcode.com/book/chapter-9-the-evolution-of-code/
This article will only highlight issues of implementation in C#; The genetic algorithm consists of the following steps
1. Generate initial population
2. Evaluate population by applying fitness (or objective) function
3. Create mating pool or write algorithm to create parents pool
4. Create new generation by mating/mixing
5. Apply mutation to the new generation
6. Repeat steps 2 to 5 until objective function is satisfied (or solution found)
Programming DNA class:
Generating letters and numbers The first issue that I have encountered is to select random letters and numbers. In order for me to do that I made a string
string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ";
It's important to notice that I included space at the end of the chars string. If you don’t do that then when you write your target phrase with spaces, you won't be able to find that solution.
String chars can be accessed the same way as any arrays by its index. For example, if you want to get letter B, you can do this:
var letterB = chars[1]
Note that in c# the index starts with 0; The random letter will be selected as follows:
Random random = new Random();
genes[i] = chars[random.Next(chars.Length)];
Randomness Processor base application runs extremely fast. As the result, if you just use random.Next() you will get a lot of exactly the same random numbers. In the test run I got 150 of the same strings that are supposed to be random. The bigger challenge to catch when you are debuging. You won't see it happening because enough time will elapse between F5 clicks.
To deal with this problem you should declare the following fields:
private static readonly Random random = new Random();
private static readonly object syncLock = new object();
And every time you generate a new random number you have to lock the thread. A lock protects access to the variables for the total count and sum of all random numbers generated on all thread
for (int i=0; i<genes.Length; i++)
{
lock (syncLock)
{
genes[i] = chars[random.Next(chars.Length)];
}
}
For more information visit MSDN https://msdn.microsoft.com/en-us/library/system.random.aspx