Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.






(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:






Qt project file


# Project created by QtCreator 2010-07-23T11:53:46
QT += core
QT -= gui
TARGET = CppGalibExample1
CONFIG += console
CONFIG -= app_bundle
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);

  //Check the best genome
  const GAGenome& best_genome = g.statistics().bestIndividual();
      << "Best genome found:\n"
      << best_genome
      << "\n";






Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.


Valid XHTML 1.0 Strict