1 #ifndef __CROSSOVER_CROSSOVER_H
2 #define __CROSSOVER_CROSSOVER_H
6 #include "chromosome.h"
7 #include "generation.h"
12 // namespace crossover {
13 template < typename _Chromosome >
17 * Type of probability of crossover chance
19 typedef float CrossoverChanceType;
22 * Type representing Chromosome Gene
24 typedef typename _Chromosome::GeneType GeneType;
27 * Probability of Crossover (0 = 0%, 1 = 100%)
29 CrossoverChanceType chance;
32 * Crossover two Chromosome's between themself.
34 * @param first first Chromosome to Crossover
35 * @param second second Chromosome to Crossover
36 * @param splitPlace Gene number on which the Genes should be swapped
37 * @return new Chromosome crossed between given two
39 _Chromosome do_cross(_Chromosome& first, _Chromosome& second, const unsigned int splitPlace) {
40 const unsigned int chromosomeSize = first.size();
43 // for (unsigned int i = 0; i < chromosomeSize; i++) {
44 // cout << first[i].get();
47 // for (unsigned int i = 0; i < chromosomeSize; i++) {
48 // cout << second[i].get();
50 // cout << "\n--------";
51 // for (unsigned int i = 0; i < chromosomeSize; i++) {
52 // if (i == splitPlace) {
60 std::vector<GeneType> crossedChromosome;
61 for (unsigned int i = 0; i < chromosomeSize; i++) {
63 crossedChromosome.push_back(first[i].get());
66 crossedChromosome.push_back(second[i].get());
71 // for (unsigned int i = 0; i < chromosomeSize; i++) {
72 // cout << crossedChromosome[i];
76 return _Chromosome(crossedChromosome);
81 * Class constructor. Initializes values.
83 * @param chance probability of Crossover (0 = 0%, 1 = 100%)
85 Crossover(const CrossoverChanceType& chance) :
90 * Invokes Crossover calculations
92 * @param _generation Generation for which the crossover should be applied
93 * @return new Generation of Chromosome's after the Crossover
95 Generation<_Chromosome> cross(Generation<_Chromosome>& _generation) {
96 const unsigned int generationSize = _generation.size();
97 std::vector<_Chromosome> newGeneration;
99 for (unsigned int i = 0; i < generationSize; i++) {
100 CrossoverChanceType random = (rand() + 1 % 10000) / 10000.0;
101 _Chromosome chromosome = _generation[i];
102 if (random < this->chance) {
103 const unsigned int chromosomeSize = chromosome.size();
104 const unsigned int splitPlace = rand() % chromosomeSize;
105 unsigned int pairedChromosome = 0;
108 * Search for different Chromosome, and crossover them together
111 pairedChromosome = rand() % generationSize;
112 } while(pairedChromosome == i);
114 chromosome = do_cross(chromosome, _generation[pairedChromosome], splitPlace);
116 newGeneration.push_back(chromosome);
119 return Generation<_Chromosome>(newGeneration);
125 #endif /* __CROSSOVER_CROSSOVER_H */