gpt4 book ai didi

c++ - 两点交叉操作

转载 作者:行者123 更新时间:2023-11-28 01:04:23 24 4
gpt4 key购买 nike

我一直在尝试为遗传算法中的两点交叉操作编写代码。首先选择两个随机基因位置。之后,两条染色体交换它们位于 btw 随机数的基因,称为 genelocation1 和 genelocatıon2。

for example  First Gene [0.3,0.2,0.4,0,0.1,0.5,0.7]
Second Gene [0.25,0.6,0.45,0.15,0.80,0.9,0.85]
rndm genelocation1=3
rdnm gnelocation2 =5
child Gene1 [0.3,0.2,0.4,0.15,0.80,0.5,0.7]
Gene2 [0.25, 0.6, 0.45, 0, 0.1,0.9,0.85]

我的问题是:因为两个数字是随机生成的,所以我无法定义像 array[genelocation2-genelocation1] 这样的数组。我该如何解决这个问题。这是我关于两点交叉的全部代码。指针可能是一个解决方案,但我不擅长指针。

代码如下:

void Xover (int mother,int father)
{
int tempo;
int Rndmgenelocation1=(rand()%ActivityNumber);
int Rndmgenelocation2=(rand()%ActivityNumber);

if (Rndmgenelocation1>Rndmgenelocation2)//sure that 2>1
{
tempo=Rndmgenelocation1;
Rndmgenelocation1=Rndmgenelocation2;
Rndmgenelocation2=tempo;
}

int size=(Rndmgenelocation2-Rndmgenelocation1);
int Temp1[size];//this makes an error

int ppp=Rndmgenelocation1;
for (int pp=Rndmgenelocation1;pp<Rndmgenelocation2;pp++)
{
Temp1[pp]=Sol_list[father].Chromosome[ppp];
ppp++;
}
int pppx=Rndmgenelocation1;
for (int ppx=Rndmgenelocation1;ppx<Rndmgenelocation2;ppx++)
{
Sol_list[father].Chromosome[ppx]=Sol_list[mother].Chromosome[pppx];
pppx++;
}
int ppplx=Rndmgenelocation1;
for (int pplx=Rndmgenelocation1;pplx<Rndmgenelocation2;pplx++)
{
Sol_list[father].Chromosome[pplx]=Temp1[ppplx];
ppplx++;
}

return;
}

最佳答案

您不能在堆栈上定义可变大小的数组。你可以使用

int *Temp1=new int[size]

那你千万不要忘记打电话

delete[] Temp1;

在你的函数结束时!

编辑:

我没有在下面测试我的代码,但下面的代码应该以更有效(也更容易理解)的方式执行您想要的操作:

#include <algorithm>
void Xover (int mother,int father)
{
int Rndmgenelocation1=(rand()%ActivityNumber);
int Rndmgenelocation2=(rand()%ActivityNumber);

if (Rndmgenelocation1>Rndmgenelocation2)//sure that 2>1
{
std::swap(Rndmgenelocation1,Rndmgenelocation2);
}

for (int pp=Rndmgenelocation1;pp<Rndmgenelocation2;pp++)
{
std::swap(Sol_list[father].Chromosome[pp],Sol_list[mother].Chromosome[pp]);
}
return;
}

编辑2:

我刚找到 here另一种更好的方法——STL 实现了一个随时可用的交叉算法。使用:

#include <algorithm>
void Xover (int mother,int father)
{
int Rndmgenelocation1=(rand()%ActivityNumber);
int Rndmgenelocation2=(rand()%ActivityNumber);

if (Rndmgenelocation1>Rndmgenelocation2)//sure that 2>1
{
std::swap(Rndmgenelocation1,Rndmgenelocation2);
}

std::swap_ranges(
Sol_list[father].Chromosome[Rndmgenelocation1],
Sol_list[father].Chromosome[Rndmgenelocation2],
Sol_list[mother].Chromosome[Rndmgenelocation1]
);

return;
}

关于c++ - 两点交叉操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7145583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com