加密算法:交叉算法



如上文遗传算法中数据结构中所讲基因 2进制编码有直接编码(Normal)和Gray编码的分以下所说算法均适用于这两种算法

假设基因 2进制编码长度为N那么这些编码的间有N-1个空隙可供交叉使用
2进制交叉算法就是如何选择空隙选择多少个空隙
以下将各走极端选择个空隙交叉单点交叉算法和选择N-1个空隙进行交叉洗牌交叉算法大致说

(1) 单点交叉
在 2进制编码中随机选择个点以这个点为界限相互交换变量

父个体1 011111110000000000
父个体2 000000001111111111
如粗体前边位置为所选择交叉点那么生成子个体为:
子个体1 011111111111111111
子个体2 000000000000000000
以下为c实现采用Gray编码直接编码类似
1/*
2Genecrossoveralgorithm
3OnePoCrossoverusingGraybinaryencoding
4
5Acrossoveroperatorthatrandomlyselectsacrossoverpo
6withinachromosomethenerchangesthetwoparentchromosomes
7atthispotoproducetwooffspring.
8
9Considerthefollowing2parentswhichhavebeenselectedfor
10crossover.The“|”symbolindicatestherandomlychosen
11crossoverpo.
12
13Parent1:11001|010
14Parent2:00100|111
15
16Aftererchangingtheparentchromosomesatthecrossover
17po,thefollowingoffspringareproduced:
18
19Offspring1:11001|111
20Offspring2:00100|010
21*/
22template<GENE>
23Gray_Binary_Single_Po_Xover_Gene_Crossover_Algorithm
24{
25public:
26voidoperator(GENE&g1,GENE&g2)const
27{
28encoding(g1);
29encoding(g2);
30assert(g1.Binary_Array.sizeg2.Binary_Array.size);
31
32normal2gray(g1);
33normal2gray(g2);
34
35constunsignedPos=_cast<unsigned>
36(g1.Binary_Array.size*ran);
37
38for(unsignedi=0;i<Pos;i)
39{
40(g1.Binary_Array[i]xorg2.Binary_Array[i])
41{
42(g1.Binary_Array[i])
43{
44g1.Binary_Array[i]=0;
45g2.Binary_Array[i]=1;
46}
47
48{
49g1.Binary_Array[i]=1;
50g2.Binary_Array[i]=0;
51}
52}
53}
54
55gray2normal(g1);
56gray2normal(g1);
57decoding(g1);
58decoding(g2);
59}
60};
61
62
63



(2)洗牌交叉
洗牌交叉就是个父基因取再上来自另外个父基因构成个新子基因
算法代码如下:

1template<GENE>
2Gray_Binary_Shuffle_Xover_Gene_Crossover_Algorithm
3{
4public:
5voidoperator(GENE&g1,GENE&g2)const
6{
7encoding(g1);
8encoding(g2);
9assert(g1.Binary_Array.sizeg2.Binary_Array.size);
10
11normal2gray(g1);
12normal2gray(g2);
13
14constunsignedSize=g1.Binary_Array.size;
15
16for(unsignedi=0;i<Size;i)
17{
18((i&1)&&
19(g1.Binary_Array[i]xorg2.Binary_Array[i])
20)
21{
22(g1.Binary_Array[i])
23{
24g1.Binary_Array[i]=0;
25g2.Binary_Array[i]=1;
26}
27
28{
29g1.Binary_Array[i]=1;
30g2.Binary_Array[i]=0;
31}
32}
33}
34
35gray2normal(g1);
36gray2normal(g1);
37decoding(g1);
38decoding(g2);
39}
40};
41
42
Tags:  rsa算法 排序算法 算法导论 加密算法

延伸阅读

最新评论

发表评论