Fixed Mutation.
[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 mutation {
13         template < typename _Chromosome>
14         class Mutation {
15         public:
16             typedef double MutationChanceType;
17             typedef typename _Chromosome::GeneType GeneType;
18         protected:
19             MutationChanceType chance;
20
21         public:
22             Mutation(MutationChanceType chance) :
23                 chance(chance) {
24             }
25
26             Generation<_Chromosome> mutate(Generation<_Chromosome> _generation) {
27                 const unsigned int generationSize = _generation.get().size();
28                 const unsigned int chromosomeSize = _generation.get()[0].get().size();
29                 vector<_Chromosome> newGeneration;
30
31                 for (unsigned int i = 0; i < generationSize; i++) {
32                     MutationChanceType random = (rand() % 10000) / 10000.0;
33
34                     _Chromosome chromosome = _generation.get()[i];
35                     if (random < this->chance) {
36                         unsigned int mutatedGene = (rand() % chromosomeSize);
37                         vector<GeneType> newChromosome = chromosome.get();
38
39                         newChromosome[mutatedGene] = GeneType(!newChromosome[mutatedGene].get());
40
41                         chromosome = _Chromosome(newChromosome);
42                     }
43                     newGeneration.push_back(chromosome);
44                 }
45                 return Generation<_Chromosome>(newGeneration);
46             }
47         };
48 //     }
49 }
50
51 #endif /* __MUTATION_MUTATION_H */