【发布时间】:2015-07-15 12:02:33
【问题描述】:
我正在使用一个点交叉来交叉两个人。假设我有两个人,例如
I1='10010011'
I2='11001101'
tmp_P 是向量存储两个单独的I1 和I2。我想在 C++ 中实现一个点交叉。对吗?
这是算法描述
fori=1 to N/2 (N is number of individual=2 in my case)
if random[0,1]<=Pc //cross prob.
pos=random_int[1,n-1]
for k=pos+1 to n //Length of individual=8 in my case
aux=tmp_P_i[k]
tmp_P_i[k]=tmp_P_(i+N/2)[k]
tmp_P_(i+N/2)[k]=aux;
end
end
end
我的问题是我混淆了pos 的索引。它是从 [0 到 n-2] 随机的吗?这样对吗?
//Random integer in range [min max]
int random_int(int min, int max) //range : [min, max]
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(min, max);
return dis(gen);
}
//One-point Crossover
vector< vector<int> > crossover(vector< vector<int> > tmp_P)
{
int pos=0;
for (int i=0;i<N/2;i++)
{
//If random number smaller than crossover probability then do Crossover
if(RND()<=Pc)
{
pos=random_int(0,n-2);//Index in C++ from 0
int aux=0;
for (int k=pos+1;k<n;k++)
{
//swat
aux=tmp_P[i][k];
tmp_P[i][k]=tmp_P[i+N/2][k];
tmp_P[i+N/2][k]=aux;
}
}
}
return tmp_P;
}
【问题讨论】:
-
是的,
std::uniform_int_distribution将生成在闭区间[a,b]上均匀分布的数字。因此,如果你想从pos+1开始你的for 循环,你必须使用n-2。但是,我建议使用random_int(0,n-1),然后从k=pos开始,因为它看起来更干净。
标签: c++ c++11 genetic-algorithm evolutionary-algorithm crossover