(C++) GAlib example 1: binary triplets evolution

February 24, 2017 · View on GitHub

 

 

 

 

 

(C++) GAlib example 1: binary triplets evolution

 

This GAlib example shows how to use genetic algorithms for a binary string genome to evolve to triplets of zeroes and ones.

 

 

Operating system: Ubuntu 10.04 LTS Lucid Lynx

IDE: Qt Creator 2.0.0

Project type: Qt4 Console Application

Compiler: G++ 4.4.1

Libraries used:

  • Galib: version 2.4.7-3, from Ubuntu Software centre ('libga-dev')
  • STL: from GCC, shipped with Qt Creator 2.0.0

 

 

 

 

 

Qt project file

 


#------------------------------------------------- # # Project created by QtCreator 2010-07-23T11:53:46 # #------------------------------------------------- QT += core QT -= gui TARGET = CppGalibExample1 CONFIG += console CONFIG -= app_bundle TEMPLATE = app LIBS += -L/usr/local/lib -lga SOURCES += main.cpp

 

 

 

 

 

Source code

 


#include <cassert> #include <iostream> #include <ga/GASimpleGA.h> #include <ga/GA2DBinStrGenome.h> //Goal genome consist of triplets of zeroes and ones: //000 111 000 111 etc. float triplet_objective(GAGenome& g) {   const GA2DBinaryStringGenome * const genome       = dynamic_cast<GA2DBinaryStringGenome*>(&g);   assert(genome && "Assume a binary string genome for triplet objective");   const int maxx = genome->width();   const int maxy = genome->height();   float score=0.0;   for(int y=0; y!=maxy; y++)   {     for(int x=0; x!=maxx; x++)     {       const int goal = (x / 3) % 2;       if(genome->gene(x,y) == goal) score+=1.0;     }   }   return score; } int main() {   //Create first genome   const int genome_length = 42;   const int ploidy = 2; //Diploid   const GA2DBinaryStringGenome first_genome(genome_length, ploidy, triplet_objective);   //Set up the genetic algorithm   GASimpleGA g(first_genome);   g.populationSize(100);   g.nGenerations(1000);   g.pMutation(0.001);   g.pCrossover(0.5);   g.evolve();   //Check the best genome   const GAGenome& best_genome = g.statistics().bestIndividual();   std::cout       << "Best genome found:\n"       << best_genome       << "\n"; }