Simple Genetic Algorithm To Evolve A String of Integers

Posted on Updated on

Genetic Algorithms are a means of optimization copied from the natural world. According to the theories of evolution, nature has a way of selecting the best (fittest) individuals to mate (Crossover) and reproduce; thus carrying on the best features of each selected individual. Even though traits from both parents are carried over into children there is still an element of randomness involved (Mutation) that gives their offspring the ability to explore their fitness landscape (adapt) to their environment. Genetic Algorithms tries to mimic this behavior with three common operators (1)Selection, (2)Crossover, (3)Mutation.

The selection operator determines how the individuals of a population are selected to mate, the most popular selection method is called elitism and this is the method that we will use in our genetic algorithm implementation.

The crossover operator determines how the parents are recombined to form offspring. We will be using single point crossover in this implementation.

Mutation inserts randomness into the genotype of each offspring giving it the ability to diversify from the features of its parents.

Implementing genetic algorithms can be seen as somewhat of an art because almost all of the code is boiler plate except for the chromosome representation used and how the fitness of each individual is calculated. These two factors usually have the most impact on the accuracy and speed of the genetic algorithm and are the most difficult to represent. These factors along with the mutation rate, crossover rate and selection method have to be tinkered with until a viable configuration is reached.

This implementation will evolve the number sequence 123456789 in that specific order.

Interesting Functions

private static void CalculateFitness(sequence seq)
var ordered = new sequence{buffer = new List<string>() {"1", "2", "3", "4", "5", "6", "7", "8", "9"}};

int result=0;
for (int i = 0; i < 9; i++)
if (ordered.buffer[i] == seq.buffer[i]) result++;
} = result;


private void Epoch(List<sequence> population)
            survivors.AddRange(population.Where(i => >= survivorThreshold));

            Mutate(population.Where(i => >= mutantThreshold));

            CrossOver(population.Where(i => >= crossoverThreshold) as IEnumerable);


            for (int i = 0; i < populationSize - survivors.Count; i++)
                var temp = GenerateSequence();

The full code listing can be found at github

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s