#include "Selection.h" //#include "Genetic.h" #include #include #include #define USED 1 #define UNUSED 0 #define DEBUG 0 #define TOUR 3 /** * the constructor * * @param c the number of chromosomes we want to select */ Selection::Selection(int c) { count = c; } /** * method that realizes the turnament selection * * @param chs the initial list of chromosomes * @param nou the final list of chromosomes (contains the selected chromosomes) */ void Selection::turnamentSelection(vector chs, vector & nou) { //srand(time(NULL)); int max_fitness = -1,max_poz = -1; int poz ; int * uz_gen = (int *) calloc(chs.size(), sizeof(int)); int * uz_crt = (int *)calloc(chs.size(), sizeof(int)); //for each chromosome I have to select for(int i = 0 ; i < count ; i ++) { //selecting TOUR individuals for(int j = 0 ; j < TOUR; ) { poz = rand() % chs.size(); if(uz_gen[poz] == UNUSED && uz_crt[poz] == UNUSED) { if(chs[poz].fitness > max_fitness) { max_fitness = chs[poz].fitness; max_poz = poz; } uz_crt[poz] = USED; j++; } } //select the best nou.push_back(chs[max_poz]); uz_gen[max_poz] = USED; /* printf("poz = %i\n", max_poz); printf("partial "); for(int j = 0 ; j < (int)chs.size() ; j ++) printf("%i ", uz_crt[j]); printf("\ngeneral "); */ if( i == count - 1 && DEBUG == 1 ) { for(int j = 0 ; j < (int)chs.size() ; j ++) printf("%i ", uz_gen[j]); printf("\n"); } for(int j = 0 ; j < (int)chs.size() ; j ++) uz_crt[j] = UNUSED; max_poz = -1; max_fitness = -1; } }