遗传算法中去除一条染色体内的闭环

xiaoxiao2021-02-28  100

最近在使用遗传算法处理图的最优化路径。因为基因位由路径节点本身表示,在随机生成新的路径点的时候有可能会与先前的重复,造成闭环,这种情况应该删去该闭环,仅保留开始的一位。其中应用了一些小技巧,记录如下:

#include<vector> #include<iostream> #include<string> using namespace std; int main(){ vector<int> vec = { 0, 2, 3 ,7 ,8 ,4,8,14 ,15 ,14 ,13 ,17 }; show(vec,"BeforeDeleteCycles:"); DeleteCycles(vec); show(vec,"AfterDeleteCycles:"); } void DeleteCycles(std::vector<int> vec){ int dupIndex_first, dupIndex_end; for (unsigned int i = 0; i < vec.size(); i++) { dupIndex_end = i ;//注意此处的用法 for (unsigned int j = i + 1; j < vec.size(); j++) { if (vec[i] == vec[j]) { dupIndex_end = j;//只需记录重复节点最后的位置即可,因此可以覆盖 } } if (dupIndex_end > i){ vec.erase(vec.begin() + i + 1, vec.begin() + dupIndex_end + 1); } } void show(std::vector<int> vec,std::string debug_name){ cout << "Debug:"<<debug_name<<endl; for (unsigned int i = 0; i != vec.size(); i++) { cout << i << " " << vec[i] << endl; } cout << endl; }

在此感谢雷神提出的建议!

转载请注明原文地址: https://www.6miu.com/read-45830.html

最新回复(0)