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 // cout << "[+] Algorithm::Selection.draw()\n";
71 this->generation = selection.draw();
72 // cout << "[+] Crossover\n";
73 this->generation = crossover.cross(this->generation);
74 // cout << "[+] Mutate\n";
75 this->generation = mutation.mutate(this->generation);
77 // cout << "New Generation:\n";
78 // this->showGeneration();
79 this->showAvgFitness();
80 this->showBestFitness();
84 void showGeneration() {
85 for (unsigned int i = 0; i < this->generation.get().size(); i++) {
86 cout << "# " << i << ") ";
87 for (unsigned int j = 0; j < this->generation.get()[i].get().size(); j++) {
88 cout << this->generation.get()[i].get()[j].get();
94 void showAvgFitness() {
96 // cout << "Fitness:\n";
97 for (unsigned int i = 0; i < this->generation.get().size(); i++) {
98 // cout << "# " << i << ") ";
99 WSTI<_Chromosome, FitnessValueType> fit(this->generation.get()[i], 0.5, 2.5);
100 // cout << fit.calculate() << "\n";
101 avg += fit.calculate();
103 cout << " " << avg / this->generation.get().size();
106 void showBestFitness() {
107 double best = -100000;
108 for (unsigned int i = 0; i < this->generation.get().size(); i++) {
109 // cout << "# " << i << ") ";
110 WSTI<_Chromosome, FitnessValueType> fit(this->generation.get()[i], 0.5, 2.5);
111 // cout << fit.calculate() << "\n";
112 double tmp = fit.calculate();
117 cout << " " << best << endl;
122 #endif /* __ALGORITHM_H */