00001 #include <algorithm>
00002 #include <iostream>
00003 #include "GLCrossoverVectorKeepMatching.h"
00004 #include "GLLogicError.h"
00005 #include "GLOrganismVector.h"
00006 #include "GLRuntimeError.h"
00007 #include "gl_utils.h"
00008
00009 using namespace std;
00010
00019 template<class T>
00020 void GLCrossoverVectorKeepMatching<T>::makeOffsprings(
00021 const vector<GLBaseOrganism*>& parents,
00022 vector<GLBaseOrganism*>& children)
00023 {
00024
00025 if (parents.size() != 2)
00026 {
00027 char errormsg[1000];
00028 sprintf(errormsg,
00029 "\nGLCrossoverVectorKeepMatching<T>::makeOffspring\n"
00030 "Can accept 2 parents only, while vector of %i parents "
00031 "was passed\n",
00032 (int)parents.size());
00033 throw GLLogicError(errormsg);
00034 }
00035
00036
00037 const GLOrganismVector<T> *parent_1 =
00038 dynamic_cast<const GLOrganismVector<T>*>(parents[0]);
00039 const GLOrganismVector<T> *parent_2 =
00040 dynamic_cast<const GLOrganismVector<T>*>(parents[1]);
00041
00042 if ((parent_1 == NULL) || (parent_2 == NULL))
00043 {
00044 char errormsg[1000];
00045 sprintf(errormsg, "\nGLCrossoverVectorKeepMatching<T>::makeOffspring\n"
00046 "One or both of parents are either of the wrong type\n"
00047 "(should be pointer to GLVectorOrganism<T>) or NULL\n");
00048 throw GLRuntimeError(errormsg);
00049 }
00050
00051 if (parent_1->getSize() != parent_2->getSize())
00052 {
00053 char errormsg[100];
00054 sprintf(errormsg, "\nGLCrossoverVectorKeepMatching<T>::makeOffspring\n"
00055 "Both parents should have the same number of genes.\n"
00056 "parent_1.getSize()= %i, parent_2.getSize() = %i\n",
00057 parent_1->getSize(), parent_2->getSize());
00058 throw GLLogicError(errormsg);
00059 }
00060
00061
00062 children.clear();
00063 int size = parent_1->getSize();
00064
00065 vector<T> new_chromosome(size);
00066
00067 vector<int> shuffled_positions;
00068
00069 vector<T> genes_to_shuffle;
00070 shuffled_positions.reserve(size);
00071 genes_to_shuffle.reserve(size);
00072 for(int i = 0; i < size; i++)
00073 {
00074 if ((*parent_1)[i] == (*parent_2)[i])
00075 {
00076 new_chromosome[i] = (*parent_1)[i];
00077 }
00078 else
00079 {
00080 shuffled_positions.push_back(i);
00081 genes_to_shuffle.push_back((*parent_1)[i]);
00082 }
00083 }
00084
00085 gl_shuffle_vector(genes_to_shuffle);
00086
00087 for(size_t i = 0; i < shuffled_positions.size(); i++)
00088 {
00089 new_chromosome[shuffled_positions[i]] = genes_to_shuffle[i];
00090 }
00091 GLOrganismVector<T>* offspring = new GLOrganismVector<T>(new_chromosome);
00092 children.push_back(offspring);
00093 }