0

I have written the code for a genetic algorithm and have the crossover function, mutation function, parent selector function and a function to transfer genes. Now I want to put it all together and would like to know if the following code is good programming practice or not.

Species Parents[popSize];
Species Children[popSize];

for(int gen = 0 ; gen < 100 ; gen++)
{
    for(int i = 0; i < popSize ; i ++)
    {
        int parentA = chooseParent(Parents);
        int parentB = chooseParent(Parents);
        crossOver(Parents[parentA] , Parents[parentB] , Children[i]);
        Children[i].mutate();
    }
    for(int i = 0; i < popSize ; i ++)
    {
        transfereGenes(Children[i], Parents[i]);
    }
}
manlio
  • 18,345
  • 14
  • 76
  • 126
user5351703
  • 31
  • 1
  • 3
  • 1
    I think this should be on https://codereview.stackexchange.com/ – Thijser Oct 26 '15 at 20:57
  • Im sorry i was unaware. Is it in violation of this stackexchange? – user5351703 Oct 26 '15 at 20:59
  • 1
    Well stackoverflow is mostly for questions of "how do I do X" while codereview is more about "I wrote this piece of code what do you think?" So if you move it you are far more likely to high quality comments. – Thijser Oct 26 '15 at 21:01

1 Answers1

0

It's a simple, clear, standard implementation of a genetic algorithm. It's enough for many application.

Anyway you could consider some points:

  • using std::vector instead of arrays
    1. it's a way to gain flexibility without losing speed (e.g. there're some variations of the basic genetic algorithm that consider variable-size populations)
    2. it allows to swap Children and Parents via the swap function (faster for large populations)
  • you can probably change the chooseParent function to extract a couple of individuals (and, in general, n individuals acting as parents) in a single "step". This is quite simple for tournament selection.
  • you should add some control parameters (probability of mutation, crossover...). Many problems are very sensitive to these parameters and you can consider different values during evolution.
  • for strictly C++ related points:
    1. you should avoid the postfix increment operator (gen++, i++)
    2. 100 is a magic number
Community
  • 1
  • 1
manlio
  • 18,345
  • 14
  • 76
  • 126