6 #include "chromosome.h"
7 #include "generation.h"
8 #include "fitness/fitness.h"
9 #include "generator/generation.h"
10 #include "selection/selection.h"
11 #include "crossover/crossover.h"
12 #include "mutation/mutation.h"
18 * Genetic Algorithm itself
20 template < typename _Chromosome, typename _Selection, typename _Crossover, typename _Mutation >
23 typedef typename _Selection::FitnessValueType FitnessValueType;
26 * Generator which draws initial population
28 generator::Generation<_Chromosome>& generator;
31 * Fitness function used in selection
33 Fitness<_Chromosome, FitnessValueType>& fitness;
48 Generation<_Chromosome> generation;
50 const int numberOfGenerations = 100;
53 generator::Generation<_Chromosome>& _generator,
54 Fitness<_Chromosome, FitnessValueType>& _fitness,
55 double crossoverChance,
56 double mutationChance) :
57 generator(_generator),
59 crossover(crossoverChance),
60 mutation(mutationChance) {
62 this->generation = this->generator.breed();
65 void searchForResult() {
66 cout << "generation avg best" << endl;
67 for(int i = 0; i < this->numberOfGenerations; i++) {
69 _Selection selection(this->generation, fitness);
70 this->generation = selection.draw();
71 this->generation = crossover.cross(this->generation);
72 this->generation = mutation.mutate(this->generation);
74 // cout << "New Generation:\n";
75 // this->showGeneration();
76 this->showAvgFitness();
77 this->showBestFitness();
81 void showGeneration() {
82 for (unsigned int i = 0; i < this->generation.get().size(); i++) {
83 cout << "# " << i << ") ";
84 for (unsigned int j = 0; j < this->generation.get()[i].get().size(); j++) {
85 cout << this->generation.get()[i].get()[j].get();
91 void showAvgFitness() {
93 for (unsigned int i = 0; i < this->generation.get().size(); i++) {
94 WSTI<_Chromosome, FitnessValueType> fit(this->generation.get()[i], 0.5, 2.5);
95 avg += fit.calculate();
97 cout << " " << avg / this->generation.get().size();
100 void showBestFitness() {
101 double best = -100000;
102 for (unsigned int i = 0; i < this->generation.get().size(); i++) {
103 WSTI<_Chromosome, FitnessValueType> fit(this->generation.get()[i], 0.5, 2.5);
104 double tmp = fit.calculate();
109 cout << " " << best << endl;
114 #endif /* __ALGORITHM_H */