Candidate GA::PMXCrossover(const Candidate& p1, const Candidate& p2){ // std::cout << "Starting crossover\n"; int startPos = std::rand() % p1.getCandidate().size(); int endPos = -1; while(endPos == -1){ int tmpPos = std::rand() % p1.getCandidate().size(); if(tmpPos > startPos) endPos = tmpPos; else if(tmpPos < startPos){ endPos = startPos; startPos = tmpPos; } } // std::cout << "swath start: " << startPos << "\nswath end: " << endPos << "\n"; std::vector<City> child(p1.getCandidate().size()); std::vector<bool> childCompletion(p1.getCandidate().size()); //COPY RANDOM SWATH OF GENES //std::copy(p1.getCandidate().begin() + startPos, // p1.getCandidate().begin() + endPos, // child.begin() + startPos); // for(int i = startPos; i <= endPos; i++){ child[i] = p1.getCandidate().at(i); } //for(const auto& c : child){ // std::cout << c << "\n"; //} for(int i = startPos; i <= endPos; i++) childCompletion[i] = true; //FIND FIRST GENE IN PARENT 2 THAT WASN'T COPIED TO CHILD for(int i = startPos; i <= endPos; i++){ auto tmpGene = std::find(child.begin(), child.end(), p2.getCandidate().at(i)); if(tmpGene == child.end()){ int destPosition = PMXCrossover_FindDestPosition(p1.getCandidate(),p2.getCandidate(),startPos,endPos,i); // std::cout << "Place " << p2.getCandidate().at(i) << " at pos " << destPosition << "\n"; child[destPosition] = p2.getCandidate().at(i); childCompletion[destPosition] = true; } } for(int i = 0; i< child.size(); i++){ if(!childCompletion[i]) child[i] = p2.getCandidate().at(i); } Candidate result = Candidate(child, distances); if(!result.isUnique()){ for(const auto& c : result.getCandidate()) std::cout << c << "\n"; throw new std::logic_error("Invalid child sequence"); } return result; }