Here is the above C ++ code with my own random class. I'm not sure if the rotation is correct, but cross-laying seems legal. At the end of the day you will not get any repetitions!
#include <array> #include <random> #include <iostream> // I converted this found code into a functional class // http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution class MyRandom { public: MyRandom() : gen(rd()) {} int nextInt(const int& max) { std::uniform_int_distribution<> dis(0, max); return dis(gen); } private: std::random_device rd; std::mt19937_64 gen; std::uniform_int_distribution<> setdis; bool disSet = false; }; void crossover(std::vector<int>& parent1, std::vector<int>& parent2) { int size = int(parent1.size()); MyRandom rand; int number1 = rand.nextInt(7); int number2 = rand.nextInt(7); int start = fmin(number1, number2); int end = fmax(number1, number2); std::vector<int> child1; std::vector<int> child2; for(int i = start; i<end; i++) { child1.push_back(parent1[i]); child2.push_back(parent2[i]); } int geneIndex = 0; int geneInparent1 = 0; int geneInparent2 = 0; for (int i = 0; i<size; i++) { geneIndex = (end + i) % size; geneInparent1 = parent1[geneIndex]; geneInparent2 = parent2[geneIndex]; bool is_there = false; for(int i1 = 0; i1<child1.size(); i1++) { if(child1[i1] == geneInparent2) { is_there = true; } } if(!is_there) { child1.push_back(geneInparent2); } bool is_there1 = false; for(int i1 = 0; i1<child2.size(); i1++) { if(child2[i1] == geneInparent1) { is_there1 = true; } } if(!is_there1) { child2.push_back(geneInparent1); } } std::rotate(child1.begin(), child1.begin()+start, child1.end()); std::rotate(child2.begin(), child2.begin()+start, child2.end()); for(int i = 0; i<size; i++) { parent1[i] = child2[i]; parent2[i] = child1[i]; } } int main(int argc, const char * argv[]) { std::vector<int> parent1 = {0, 1, 2, 3, 4, 5, 6, 7}; std::vector<int> parent2 = {7, 6, 5, 4, 3, 2, 1, 0}; for(int i = 0; i<8; i++) { std::cout << parent1[i] << " "; } std::cout << std::endl; for(int i = 0; i<8; i++) { std::cout << parent2[i] << " "; } std::cout << std::endl; crossover(parent1, parent2); for(int i = 0; i<8; i++) { std::cout << parent1[i] << " "; } std::cout << std::endl; for(int i = 0; i<8; i++) { std::cout << parent2[i] << " "; } std::cout << std::endl; return 0; }
source share