1 | #include "Selection.h" |
---|
2 | //#include "Genetic.h" |
---|
3 | #include <time.h> |
---|
4 | #include <stdlib.h> |
---|
5 | #include <stdio.h> |
---|
6 | |
---|
7 | #define USED 1 |
---|
8 | #define UNUSED 0 |
---|
9 | |
---|
10 | #define DEBUG 0 |
---|
11 | |
---|
12 | #define TOUR 3 |
---|
13 | |
---|
14 | /** |
---|
15 | * the constructor |
---|
16 | * |
---|
17 | * @param c the number of chromosomes we want to select |
---|
18 | */ |
---|
19 | Selection::Selection(int c) |
---|
20 | { |
---|
21 | count = c; |
---|
22 | } |
---|
23 | |
---|
24 | /** |
---|
25 | * method that realizes the turnament selection |
---|
26 | * |
---|
27 | * @param chs the initial list of chromosomes |
---|
28 | * @param nou the final list of chromosomes (contains the selected chromosomes) |
---|
29 | */ |
---|
30 | void Selection::turnamentSelection(vector<Chromosome> chs, vector<Chromosome> & nou) |
---|
31 | { |
---|
32 | //srand(time(NULL)); |
---|
33 | int max_fitness = -1,max_poz = -1; |
---|
34 | int poz ; |
---|
35 | int * uz_gen = (int *) calloc(chs.size(), sizeof(int)); |
---|
36 | int * uz_crt = (int *)calloc(chs.size(), sizeof(int)); |
---|
37 | //for each chromosome I have to select |
---|
38 | for(int i = 0 ; i < count ; i ++) |
---|
39 | { |
---|
40 | //selecting TOUR individuals |
---|
41 | for(int j = 0 ; j < TOUR; ) |
---|
42 | { |
---|
43 | poz = rand() % chs.size(); |
---|
44 | if(uz_gen[poz] == UNUSED && uz_crt[poz] == UNUSED) |
---|
45 | { |
---|
46 | if(chs[poz].fitness > max_fitness) |
---|
47 | { |
---|
48 | max_fitness = chs[poz].fitness; |
---|
49 | max_poz = poz; |
---|
50 | } |
---|
51 | uz_crt[poz] = USED; |
---|
52 | j++; |
---|
53 | } |
---|
54 | } |
---|
55 | //select the best |
---|
56 | nou.push_back(chs[max_poz]); |
---|
57 | uz_gen[max_poz] = USED; |
---|
58 | |
---|
59 | /* printf("poz = %i\n", max_poz); |
---|
60 | printf("partial "); |
---|
61 | for(int j = 0 ; j < (int)chs.size() ; j ++) |
---|
62 | printf("%i ", uz_crt[j]); |
---|
63 | printf("\ngeneral "); |
---|
64 | */ if( i == count - 1 && DEBUG == 1 ) |
---|
65 | { |
---|
66 | for(int j = 0 ; j < (int)chs.size() ; j ++) |
---|
67 | printf("%i ", uz_gen[j]); |
---|
68 | printf("\n"); |
---|
69 | } |
---|
70 | |
---|
71 | for(int j = 0 ; j < (int)chs.size() ; j ++) |
---|
72 | uz_crt[j] = UNUSED; |
---|
73 | max_poz = -1; |
---|
74 | max_fitness = -1; |
---|
75 | } |
---|
76 | } |
---|