014ca7066ed0e76b30d6fe7ad5c6ee9d7948ef1b
[genetic.git] / src / mutation / mutation.h
1 #ifndef __MUTATION_MUTATION_H
2 #define __MUTATION_MUTATION_H
3
4 #include <iostream>
5
6 #include "chromosome.h"
7 #include "generation.h"
8
9 using namespace std;
10
11 namespace genetic {
12 //     namespace crossover {
13         template < typename _Chromosome>
14         class Mutation {
15         public:
16             typedef double MutationChanceType;
17         protected:
18             MutationChanceType chance;
19
20         public:
21             Mutation(MutationChanceType chance) :
22                 chance(chance) {
23             }
24
25             Generation<_Chromosome> mutate(Generation<_Chromosome> _generation) {
26                 const unsigned int generationSize = _generation.get().size();
27                 const unsigned int chromosomeSize = _generation.get()[0].get().size();
28                 vector<_Chromosome> newGeneration;
29
30                 for (unsigned int i = 0; i < generationSize; i++) {
31                     MutationChanceType random = (rand() % 10000) / 10000.0;
32 //                     cout << " Mutation chance: " << chance << ", random: " << random << "\n";
33                     newGeneration.push_back(_generation.get()[i]);
34
35                     if (random < this->chance) {
36 //                         cout << " > Mutated!\n";
37                         unsigned int which = (rand() % chromosomeSize);
38                         newGeneration[i].get()[which] = !newGeneration[i].get()[which].get();
39                     }
40                 }
41                 return Generation<_Chromosome>(newGeneration);
42             }
43         };
44 //     }
45 }
46
47 #endif /* __MUTATION_MUTATION_H */