countingOnes.cpp
#include "EALib/PopulationT.h"
double ones(const std::vector< bool >& x)
{
unsigned i;
double sum;
for (sum = 0., i = 0; i < x.size(); sum += x[ i++ ]);
return sum;
}
int main(int argc, char **argv)
{
const unsigned PopSize = 20;
const unsigned Dimension = 200;
const unsigned Iterations = 1000;
const unsigned Interval = 10;
const unsigned NElitists = 1;
const unsigned Omega = 5;
const unsigned CrossPoints = 2;
const double CrossProb = 0.6;
const double FlipProb = 1. / Dimension;
unsigned i, t;
Rng::seed(argc > 1 ? atoi(argv[ 1 ]) : 1234);
PopulationT<bool> parents(PopSize, ChromosomeT< bool >(Dimension));
PopulationT<bool> offsprings(PopSize, ChromosomeT< bool >(Dimension));
std::vector< double > window(Omega);
parents .setMaximize();
offsprings.setMaximize();
for (i = 0; i < parents.size(); ++i)
parents[ i ][ 0 ].initialize();
if (NElitists > 0)
for (i = 0; i < parents.size(); ++i)
parents[ i ].setFitness(ones(parents[ i ][ 0 ]));
for (t = 0; t < Iterations; ++t) {
offsprings = parents;
for (i = 0; i < offsprings.size() - 1; i += 2)
if (Rng::coinToss(CrossProb))
offsprings[ i ][ 0 ].crossover(offsprings[ i+1 ][ 0 ],
CrossPoints);
for (i = 0; i < offsprings.size(); ++i)
offsprings[ i ][ 0 ].flip(FlipProb);
for (i = 0; i < offsprings.size(); ++i)
offsprings[ i ].setFitness(ones(offsprings[ i ][ 0 ]));
offsprings.linearDynamicScaling(window, t);
parents.selectProportional(offsprings, NElitists);
if (t % Interval == 0)
std::cout << t << "\tbest value = "
<< parents.best().fitnessValue() << "\n";
}
if(parents.best().fitnessValue()>=200) exit(EXIT_SUCCESS);
else exit(EXIT_FAILURE);
}