详细介绍如何利用各种语言(C++,C,JAV等)实现遗传算法

合集下载

遗传算法运算过程

遗传算法运算过程

遗传算法运算过程遗传算法是一种基于生物进化原理的优化算法,它模拟了生物进化过程中的选择、交叉和变异等操作,通过逐代迭代的方式不断优化问题的解。

本文将从遗传算法的运算过程入手,详细介绍其基本原理和具体步骤。

一、遗传算法的基本原理遗传算法的基本原理是模拟自然界中生物的进化过程,其中包括选择、交叉和变异等操作。

其核心思想是通过不断地对候选解进行优胜劣汰,逐渐逼近最优解。

二、遗传算法的基本步骤遗传算法的运算过程可以分为初始化、适应度评估、选择、交叉、变异和终止条件判断等步骤。

1. 初始化需要随机生成一组初始种群,其中每个个体都是问题的一个可能解。

这些个体可以用二进制编码或其他编码方式表示,具体取决于问题的特点。

2. 适应度评估对每个个体进行适应度评估,即根据问题的目标函数或约束条件,计算出每个个体的适应度值。

适应度值反映了个体对问题的解的质量。

3. 选择通过选择操作,从当前种群中选择一部分个体作为下一代的父代。

选择操作的原则是适应度高的个体被选中的概率较大,以保留优良基因。

4. 交叉选择出的父代个体进行交叉操作,生成新的子代个体。

交叉操作通过模拟生物繁殖中的基因组合,将父代个体的某些基因片段进行交换,产生具有新基因组合的子代个体。

5. 变异在交叉操作后,对新生成的子代个体进行变异操作。

变异操作是模拟生物进化中的基因突变,通过对个体的某些基因进行微小的随机变化,引入新的基因组合,以增加搜索空间。

6. 终止条件判断在每一代迭代完成后,需要判断是否满足终止条件。

终止条件可以是达到预定的迭代次数,或者找到了满足问题要求的最优解。

7. 迭代更新如果终止条件未满足,就进行下一代的迭代更新。

将新生成的子代个体与原种群进行合并,形成新的种群,并继续进行适应度评估、选择、交叉和变异等操作,直到满足终止条件。

三、遗传算法的应用范围遗传算法在优化问题的求解中具有广泛的应用。

它可以解决许多实际问题,例如旅行商问题、车辆路径规划、机器学习模型参数优化等。

遗传算法的基本原理与流程

遗传算法的基本原理与流程

遗传算法的基本原理与流程遗传算法是一种模拟生物进化过程的优化算法,它通过模拟自然选择、交叉和变异等过程,逐步搜索最优解。

本文将介绍遗传算法的基本原理与流程。

一、基本原理遗传算法的基本原理是基于达尔文的进化论和孟德尔的遗传学理论。

它将问题的解表示为一个个体的染色体,染色体由基因组成。

每个基因代表问题的一个变量或决策。

通过改变基因的组合,可以得到不同的解。

而适应度函数则用来评估每个个体的适应程度,即解的优劣程度。

遗传算法的核心思想是通过模拟自然选择、交叉和变异等过程,逐步优化解的质量。

在自然选择中,适应度高的个体有更大的概率被选择为父代,而适应度低的个体则有较小的概率被选择。

交叉操作模拟了生物的基因交换过程,将两个父代个体的染色体片段进行交叉,生成新的个体。

变异操作则模拟了基因突变的过程,通过改变染色体中的基因值,引入新的解。

二、流程遗传算法的流程一般包括初始化、选择、交叉、变异和更新等步骤。

1. 初始化:首先,需要确定问题的解空间和染色体编码方式。

然后,随机生成一组初始个体作为种群。

2. 选择:根据适应度函数,选择适应度较高的个体作为父代。

常见的选择方法有轮盘赌选择、锦标赛选择等。

3. 交叉:从父代中选取两个个体进行交叉操作,生成新的个体。

交叉操作可以是单点交叉、多点交叉或均匀交叉等。

4. 变异:对新生成的个体进行变异操作,引入新的解。

变异操作可以是位变异、插入变异或交换变异等。

5. 更新:根据适应度函数,选择新生成的个体和原始个体中适应度较高的个体,更新种群。

以上步骤可以迭代执行,直到满足终止条件,例如达到最大迭代次数或找到满意的解。

三、应用与优势遗传算法广泛应用于组合优化、函数优化、机器学习等领域。

它具有以下优势:1. 全局搜索能力:遗传算法能够在解空间中进行全局搜索,避免陷入局部最优解。

2. 并行性:由于遗传算法的并行性,可以同时处理多个个体,加快搜索速度。

3. 适应性:遗传算法能够自适应地调整搜索策略,根据不同问题的特点进行优化。

遗传算法原理及应用

遗传算法原理及应用

遗传算法原理及应用介绍遗传算法是一种受生物进化理论启发的优化算法,它模拟了自然界中的基因编码、交叉、变异和选择等过程。

遗传算法被广泛应用于求解复杂问题,如优化问题、搜索问题、机器学习等领域。

本文将介绍遗传算法的基本原理、流程以及在不同领域中的应用。

基本原理遗传算法的基本原理是通过模拟进化过程来搜索最优解。

算法通过构建一个种群,每个个体都代表了一个解。

通过遗传操作,包括选择、交叉和变异,不断改进种群中的个体,使其逐步逼近最优解。

1. 初始化种群遗传算法的第一步是初始化一个种群,种群中的个体表示待解决问题的一个可能解。

个体可以用二进制编码、整数编码、浮点编码等方式表示。

种群的大小和个体的编码方式会直接影响算法的搜索能力和效率。

2. 适应度评估每个个体都会通过适应度函数进行评估,适应度函数衡量了个体的适应程度,即其解决问题的能力。

适应度函数的选择依赖于具体问题的特点,如最大化问题可以使用目标函数值作为适应度,最小化问题可以使用目标函数的倒数或负值作为适应度。

3. 选择操作选择操作通过概率选择机制从种群中选择个体,用于构建下一代种群。

适应度高的个体被选中的概率较大,从而保留有较好的性状。

选择算子的选择有多种方法,如轮盘赌选择、锦标赛选择等,这些方法可以根据具体问题的特点进行调整。

4. 交叉操作交叉操作模拟了自然界中基因的交换过程,通过交换两个个体的染色体片段来产生新的个体。

交叉操作能够将两个个体的优良特性进行组合,从而产生具有更好适应度的后代。

交叉操作的方式多种多样,如单点交叉、多点交叉、均匀交叉等。

5. 变异操作变异操作模拟了自然界中基因的突变过程,通过改变个体的某些基因来产生新的个体。

变异操作保持了种群的多样性,并有可能引入新的解决方案。

变异操作的方式也有多种,如位变异、边界变异、非均匀变异等。

6. 更新种群经过选择、交叉和变异操作后,生成了下一代种群。

通过不断迭代以上步骤,种群的适应度逐渐提高,优秀的个体会逐渐占据主导地位。

遗传算法的原理和应用

遗传算法的原理和应用

遗传算法的原理和应用随着计算机的迅速发展,人工智能已经成为了研究热点之一。

在人工智能的领域中,遗传算法是一种非常重要的算法,被广泛应用在优化问题和搜索问题中。

遗传算法的原理遗传算法是一种基于自然界的进化原理的计算方法。

它模拟了自然选择和遗传的基本原理,从而搜索最优解。

遗传算法具有很强的适应性和鲁棒性,可以在变化的环境中不断进化。

遗传算法包括三个操作:选择、交叉和变异。

首先,从当前群体中选出适应度最高的个体,并复制其基因,用于下一代。

其次,对于两个个体,将它们交叉生成新的个体。

最后,通过随机变异,产生新的基因,以增加多样性。

遗传算法的应用遗传算法在很多领域中有着广泛的应用。

1.优化在最优化领域,遗传算法被用于解决各种复杂问题,如连续和离散函数的优化,组合优化和非线性优化。

例如,可以使用遗传算法来优化复杂的函数和模型参数。

2.机器学习遗传算法在机器学习领域中也有广泛的应用,可以嵌入到神经网络中,以更快的速度寻找最合适的权值和拓扑结构。

3.智能控制在智能控制方面,遗传算法可以用于各种复杂问题的决策。

例如,可以使用遗传算法来选择决策参数,以达到最优效果。

4.数据挖掘遗传算法被广泛应用于数据挖掘中,可以用于聚类,分类,预测和关联规则发现等问题。

总结遗传算法是一种重要的算法,具有很强的适应性和鲁棒性。

它可以被用于各种复杂问题的优化和搜索,并且在机器学习、智能控制和数据挖掘等领域中有着广泛的应用。

当然,随着计算机技术的不断发展,遗传算法也将有着更广阔的应用前景。

遗传算法的步骤

遗传算法的步骤

遗传算法的步骤遗传算法是一种基于自然选择和遗传机制的优化算法,它模拟了生物进化的过程,通过不断地迭代和优化,寻找最优解。

下面将介绍遗传算法的步骤。

1. 初始化种群遗传算法的第一步是初始化种群,即随机生成一组初始解。

这些解可以是随机生成的,也可以是根据问题的特点和经验生成的。

种群的大小和组成对算法的效果有很大的影响,一般来说,种群越大,搜索空间越广,但计算时间也会增加。

2. 选择操作选择操作是遗传算法的核心步骤之一,它模拟了自然选择的过程。

在选择操作中,根据适应度函数的值,选择一部分优秀的个体作为下一代的父代。

适应度函数的设计非常重要,它决定了个体的生存能力和繁殖能力。

3. 交叉操作交叉操作是遗传算法的另一个核心步骤,它模拟了生物的交配过程。

在交叉操作中,从父代中选择两个个体,通过交叉操作生成新的个体。

交叉操作的方式有很多种,如单点交叉、多点交叉、均匀交叉等。

4. 变异操作变异操作是遗传算法的最后一步,它模拟了生物的突变过程。

在变异操作中,对新生成的个体进行一定的变异操作,以增加搜索空间和避免陷入局部最优解。

变异操作的方式也有很多种,如位变异、反转变异、插入变异等。

5. 重复迭代遗传算法的迭代过程是不断重复选择、交叉和变异操作的过程,直到达到预设的停止条件。

停止条件可以是达到最大迭代次数、达到最优解或达到一定的误差范围等。

在迭代过程中,每一代的种群都会不断进化和优化,直到找到最优解。

遗传算法是一种非常有效的优化算法,它模拟了生物进化的过程,通过不断的选择、交叉和变异操作,寻找最优解。

在实际应用中,需要根据问题的特点和经验来选择适当的参数和操作方式,以达到最优的效果。

遗传算法的使用方法和技巧指南

遗传算法的使用方法和技巧指南

遗传算法的使用方法和技巧指南遗传算法是一种启发式优化算法,它模拟了自然界中的生物进化过程来解决问题。

它具有强大的搜索能力和全局优化能力,在各个领域都有广泛的应用。

本文将介绍遗传算法的基本原理、使用方法以及一些重要的技巧指南。

一、遗传算法的基本原理遗传算法基于生物进化的思想,通过模拟人工选择、交叉和变异等过程来生成和更新解的种群,并利用适应度函数对种群进行评估和选择,以期望通过迭代的方式找到最优解。

遗传算法的基本流程如下:1. 初始化种群:随机生成一组个体作为初始种群。

2. 适应度评估:根据问题的特定要求,计算每个个体的适应度值。

3. 选择操作:利用适应度值选择父代个体进行繁殖,常用的选择算法有轮盘赌选择和竞争选择等。

4. 交叉操作:通过交叉运算生成新的后代个体,交叉操作能够保留父代的有益特征。

5. 变异操作:对交叉后的个体进行基因的随机变异,增加种群的多样性。

6. 替换操作:根据一定的规则,用新生成的后代个体替换原始种群中的一部分个体。

7. 终止条件判断:根据迭代次数或者达到某个预定义的解的条件,判断是否终止迭代。

8. 返回最优解。

二、遗传算法的使用方法为了正确有效地使用遗传算法,我们需要遵循以下几个步骤:1. 理解问题:首先,要准确理解问题的特性和要求,包括确定问题的目标函数、约束条件等。

只有对问题有清晰的认识,才能设计合适的遗传算法。

2. 设计编码方案:将问题的解表示为染色体的编码方案,更好的编码方案可以减少解空间的搜索范围。

常用的编码方式有二进制、浮点数、整数等。

3. 确定适应度函数:根据问题的特点,设计合适的适应度函数用于度量个体的优劣。

适应度函数应能够将问题的目标转化为一个数值,使得数值越大越好或者越小越好。

4. 选择操作:选择操作决定了如何根据适应度值选择父代个体。

常用的选择算法有轮盘赌选择、竞争选择、排名选择等。

轮盘赌选择是普遍应用的一种方法,根据个体的适应度值按比例选择。

5. 交叉操作:交叉操作决定了如何生成新的后代个体。

遗传算法入门指南

遗传算法入门指南

遗传算法入门指南遗传算法是一种模拟自然进化过程的优化算法,通过模拟遗传、变异和选择等过程来搜索问题的最优解。

它是一种非常强大和灵活的算法,可以应用于各种问题的求解,如优化问题、机器学习、人工智能等。

本文将为您介绍遗传算法的基本原理、应用场景以及实现步骤,帮助您入门遗传算法。

一、遗传算法的基本原理遗传算法的基本原理是模拟自然界中的进化过程,通过遗传、变异和选择等操作来搜索问题的最优解。

它的基本步骤包括:初始化种群、评估适应度、选择操作、交叉操作、变异操作和终止条件判断。

1. 初始化种群首先,需要随机生成一组初始解作为种群的个体。

这些个体可以是问题的任意一个可能解,也可以是随机生成的解。

2. 评估适应度对于每个个体,需要计算其适应度值,即该个体解决问题的好坏程度。

适应度值可以根据问题的具体情况来定义,一般是通过一个评估函数来计算。

3. 选择操作选择操作是根据适应度值来选择个体进入下一代的过程。

适应度值高的个体有更大的概率被选择,而适应度值低的个体有较小的概率被选择。

这样可以保留优秀的个体,并逐渐提高种群的整体适应度。

4. 交叉操作交叉操作是模拟遗传中的基因交换过程,通过交换个体的染色体片段来产生新的个体。

交叉操作可以增加种群的多样性,并加速搜索过程。

5. 变异操作变异操作是模拟基因突变的过程,通过改变个体染色体中的某些基因来产生新的个体。

变异操作可以引入新的解空间,避免陷入局部最优解。

6. 终止条件判断在达到一定条件时,遗传算法会停止搜索过程并输出最优解。

终止条件可以是达到最大迭代次数、找到满足要求的解等。

二、遗传算法的应用场景遗传算法可以应用于各种问题的求解,特别是那些复杂、多变的问题。

以下是一些常见的应用场景:1. 优化问题遗传算法可以应用于各种优化问题,如函数最优化、组合优化、路径规划等。

通过搜索问题的解空间,找到最优解或接近最优解。

2. 机器学习遗传算法可以用于机器学习中的特征选择、参数优化等问题。

遗传算法 算法原理

遗传算法 算法原理

遗传算法算法原理(原创实用版)目录1.遗传算法的概述2.遗传算法的原理3.遗传算法的应用正文一、遗传算法的概述遗传算法(Genetic Algorithm,简称 GA)是一种模拟自然界生物进化过程的优化算法。

其核心思想是基于自然选择、遗传和突变等生物学原理,通过群体中的个体在不断迭代中进行优胜劣汰,达到解决问题和优化目标的效果。

遗传算法在解决复杂问题、非线性问题和全局最优解问题等方面具有较强的优势,广泛应用于各个领域。

二、遗传算法的原理1.遗传操作遗传算法的基本操作包括选择、交叉和变异。

选择操作是根据适应度函数对当前群体中的个体进行评估,选择优秀个体进行繁殖。

交叉操作是将选中的优秀个体进行染色体互换,产生新的后代。

变异操作是在后代中随机选择某个位点进行变异,以一定的概率产生新的特性。

2.适应度函数适应度函数是遗传算法中的重要概念,用于评估每个个体的优劣程度。

适应度函数的取值范围为 [0, 1],其中 1 表示最优解,0 表示最劣解。

在遗传算法中,适应度函数的取值会直接影响到个体的选择和淘汰。

3.遗传算法的基本流程遗传算法的基本流程如下:(1)初始化种群:创建一个初始种群,包括多个随机生成的个体,每个个体表示一个解。

(2)评估适应度:计算种群中每个个体的适应度值。

(3)选择操作:根据适应度值对种群进行选择,选择一定数量的优秀个体进行繁殖。

(4)交叉操作:对选中的优秀个体进行染色体互换,生成新的后代。

(5)变异操作:在后代中随机选择某个位点进行变异,以一定的概率产生新的特性。

(6)更新种群:将新产生的后代替换掉原种群中一些适应度较低的个体,形成新的种群。

(7)重复步骤 2-6,直至满足停止条件。

三、遗传算法的应用遗传算法在许多领域都取得了显著的应用成果,如机器学习、控制系统、信号处理、图像处理、运筹学等。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

%TSP问题(又名:旅行商问题,货郎担问题)遗传算法通用matlab程序 (2)一个C++的程序: (4)C语言程序: (8)改进后用来求解VRP问题的Delphi程序: (21)%TSP问题(又名:旅行商问题,货郎担问题)遗传算法通用matlab程序%D是距离矩阵,n为种群个数,建议取为城市个数的1~2倍,%C为停止代数,遗传到第C代时程序停止,C的具体取值视问题的规模和耗费的时间而定%m为适应值归一化淘汰加速指数,最好取为1,2,3,4 ,不宜太大%alpha为淘汰保护指数,可取为0~1之间任意小数,取1时关闭保护功能,最好取为0.8~1.0 %R为最短路径,Rlength为路径长度function [R,Rlength]=geneticTSP(D,n,C,m,alpha)[N,NN]=size(D);farm=zeros(n,N);%用于存储种群for i=1:nfarm(i,:)=randperm(N);%随机生成初始种群endR=farm(1,:);%存储最优种群len=zeros(n,1);%存储路径长度fitness=zeros(n,1);%存储归一化适应值counter=0;while counter<Cfor i=1:nlen(i,1)=myLength(D,farm(i,:));%计算路径长度endmaxlen=max(len);minlen=min(len);fitness=fit(len,m,maxlen,minlen);%计算归一化适应值rr=find(len==minlen);R=farm(rr(1,1),:);%更新最短路径FARM=farm;%优胜劣汰,nn记录了复制的个数nn=0;for i=1:nif fitness(i,1)>=alpha*randnn=nn+1;FARM(nn,:)=farm(i,:);endendFARM=FARM(1:nn,:);[aa,bb]=size(FARM);%交叉和变异while aa<nif nn<=2nnper=randperm(2);elsennper=randperm(nn);endA=FARM(nnper(1),:);B=FARM(nnper(2),:);[A,B]=intercross(A,B);FARM=[FARM;A;B];[aa,bb]=size(FARM);endif aa>nFARM=FARM(1:n,:);%保持种群规模为nendfarm=FARM;clear FARMcounter=counter+1endRlength=myLength(D,R);function [a,b]=intercross(a,b)L=length(a);if L<=10%确定交叉宽度W=1;elseif ((L/10)-floor(L/10))>=rand&&L>10W=ceil(L/10);elseW=floor(L/10);endp=unidrnd(L-W+1);%随机选择交叉范围,从p到p+W for i=1:W%交叉x=find(a==b(1,p+i-1));y=find(b==a(1,p+i-1));[a(1,p+i-1),b(1,p+i-1)]=exchange(a(1,p+i-1),b(1,p+i-1)); [a(1,x),b(1,y)]=exchange(a(1,x),b(1,y));endfunction [x,y]=exchange(x,y)x=y;y=temp;% 计算路径的子程序function len=myLength(D,p)[N,NN]=size(D);len=D(p(1,N),p(1,1));for i=1:(N-1)len=len+D(p(1,i),p(1,i+1));end%计算归一化适应值子程序function fitness=fit(len,m,maxlen,minlen)fitness=len;for i=1:length(len)fitness(i,1)=(1-((len(i,1)-minlen)/(maxlen-minlen+0.000001))).^m; end一个C++的程序://c++的程序#include<iostream.h>#include<stdlib.h>template<class T>class Graph{public:Graph(int vertices=10){n=vertices;e=0;}~Graph(){}virtual bool Add(int u,int v,const T& w)=0;virtual bool Delete(int u,int v)=0;virtual bool Exist(int u,int v)const=0;int V ertices()const{return n;}int Edges()const{return e;}protected:int n;};template<class T>class MGraph:public Graph<T>{public:MGraph(int V ertices=10,T noEdge=0);~MGraph();bool Add(int u,int v,const T& w);bool Delete(int u,int v);bool Exist(int u,int v)const;void Floyd(T**& d,int**& path);void print(int V ertices);private:T NoEdge;T** a;};template<class T>MGraph<T>::MGraph(int V ertices,T noEdge){n=V ertices;NoEdge=noEdge;a=new T* [n];for(int i=0;i<n;i++){a[i]=new T[n];a[i][i]=0;for(int j=0;j<n;j++)if(i!=j)a[i][j]=NoEdge;}}template<class T>MGraph<T>::~MGraph(){for(int i=0;i<n;i++)delete[]a[i];delete[]a;}template<class T>bool MGraph<T>::Exist(int u,int v)const{if(u<0||v<0||u>n-1||v>n-1||u==v||a[u][v]==NoEdge)return false; return true;}template<class T>bool MGraph<T>::Add(int u,int v,const T& w){if(u<0||v<0||u>n-1||v>n-1||u==v||a[u][v]!=NoEdge){ cerr<<"BadInput!"<<endl;return false;}a[u][v]=w;e++;return true;}template<class T>bool MGraph<T>:delete(int u,int v){if(u<0||v<0||u>n-1||v>n-1||u==v||a[u][v]==NoEdge){ cerr<<"BadInput!"<<endl;return false;}a[u][v]=NoEdge;e--;return true;}template<class T>void MGraph<T>::Floyd(T**& d,int**& path) {d=new T* [n];path=new int* [n];for(int i=0;i<n;i++){d[i]=new T[n];path[i]=new int[n];for(int j=0;j<n;j++){d[i][j]=a[i][j];if(i!=j&&a[i][j]<NoEdge)path[i][j]=i;else path[i][j]=-1;}}for(int k=0;k<n;k++){for(i=0;i<n;i++)for(int j=0;j<n;j++)if(d[i][k]+d[k][j]<d[i][j]){d[i][j]=d[i][k]+d[k][j];path[i][j]=path[k][j];}}}template<class T>void MGraph<T>::print(int V ertices){for(int i=0;i<V ertices;i++)for(int j=0;j<V ertices;j++){cout<<a[i][j]<<' ';if(j==V ertices-1)cout<<endl; }}#define noEdge 10000#include<iostream.h>void main(){cout<<"请输入该图的节点数:"<<endl;int vertices;cin>>vertices;MGraph<float> b(vertices,noEdge);cout<<"请输入u,v,w:"<<endl;int u,v;float w;cin>>u>>v>>w;while(w!=noEdge){//u=u-1;b.Add(u-1,v-1,w);b.Add(v-1,u-1,w);cout<<"请输入u,v,w:"<<endl;cin>>u>>v>>w;}b.print(vertices);int** Path;int**& path=Path;float** D;float**& d=D;b.Floyd(d,path);for(int i=0;i<vertices;i++){for(int j=0;j<vertices;j++){cout<<Path[i][j]<<' ';if(j==vertices-1)cout<<endl;}}int *V;V=new int[vertices+1];cout<<"请输入任意一个初始H-圈:"<<endl; for(int n=0;n<=vertices;n++){cin>>V[n];}for(n=0;n<55;n++){for(i=0;i<n-1;i++){for(int j=0;j<n-1;j++){if(i+1>0&&j>i+1&&j<n-1){if(D[V[i]][V[j]]+D[V[i+1]][V[j+1]]<D[V[i]][V[i+1]]+D[V[j]][V[j+1]]){ int l;l=V[i+1];V[i+1]=V[j];V[j]=l;}}}}}float total=0;cout<<"最小回路:"<<endl;for(i=0;i<=vertices;i++){cout<<V[i]+1<<' ';}cout<<endl;for(i=0;i<vertices;i++)total+=D[V[i]][V[i+1]];cout<<"最短路径长度:"<<endl;cout<<total;}C语言程序:#include<stdio.h>#include<stdlib.h>#include<math.h>#include<alloc.h>#include<conio.h>#include<float.h>#include<time.h>#include<graphics.h>#include<bios.h>#define maxpop 100#define maxstring 100struct pp{unsigned char chrom[maxstring];float x,fitness;unsigned int parent1,parent2,xsite;};struct pp *oldpop,*newpop,*p1;unsigned int popsize,lchrom,gem,maxgen,co_min,jrand;unsigned int nmutation,ncross,jcross,maxpp,minpp,maxxy;float pcross,pmutation,sumfitness,avg,max,min,seed,maxold,oldrand[maxstring]; unsigned char x[maxstring],y[maxstring][ ];float *dd,ff,maxdd,refpd,fm[201];FILE *fp,*fp1;float objfunc(float);void statistics();int select();int flip(float);int crossover();void generation();void initialize();void report();float decode();void crtinit();void inversion();float random1();void randomize1();main(){unsigned int gen,k,j,tt;char fname[10];float ttt;clrscr();co_min=0;if((oldpop=(struct pp *)farmalloc(maxpop*sizeof(struct pp)))==NULL){printf("memory requst fail!\n");exit(0);}if((dd=(float *)farmalloc(maxstring*maxstring*sizeof(float)))==NULL) {printf("memory requst fail!\n");exit(0);}if((newpop=(struct pp *)farmalloc(maxpop*sizeof(struct pp)))==NULL) {printf("memory requst fail!\n");exit(0);}if((p1=(struct pp *)farmalloc(sizeof(struct pp)))==NULL){printf("memory requst fail!\n");exit(0);}for(k=0;k<maxpop;k++) oldpop[k].chrom[0]='\0';for(k=0;k<maxpop;k++) newpop[k].chrom[0]='\0';printf("Enter Result Data Filename:");gets(fname);if((fp=fopen(fname,"w+"))==NULL){printf("cannot open file\n");exit(0);}gen=0;randomize();initialize();fputs("this is result of the TSP problem:",fp);fprintf(fp,"city: %2d psize: %3d Ref.TSP_path: %f\n",lchrom,popsize,refpd); fprintf(fp,"Pc: %f Pm: %f Seed: %f\n",pcross,pmutation,seed);fprintf(fp,"X site:\n");for(k=0;k<lchrom;k++){if((k%16)==0) fprintf(fp,"\n");fprintf(fp,"%5d",x[k]);}fprintf(fp,"\n Y site:\n");for(k=0;k<lchrom;k++){if((k%16)==0) fprintf(fp,"\n");fprintf(fp,"%5d",y[k]);}fprintf(fp,"\n");crtinit();statistics(oldpop);report(gen,oldpop);getch();maxold=min;fm[0]=100.0*oldpop[maxpp].x/ff;do {gen=gen+1;generation();statistics(oldpop);if(max>maxold){maxold=max;co_min=0;}fm[gen%200]=100.0*oldpop[maxpp].x/ff;report(gen,oldpop);gotoxy(30,25);ttt=clock()/18.2;printf("Run Clock: %2d: %2d: %4.2f",tt/60,tt%60,ttt-tt*60.0); printf("Min=%6.4f Nm:%d\n",min,co_min);}while((gen<100)&&!bioskey(1));printf("\n gen= %d",gen);do{gen=gen+1;generation();statistics(oldpop);if(max>maxold){maxold=max;co_min=0;}fm[gen%200]=100.0*oldpop[maxpp].x/ff;report(gen,oldpop);if((gen%100)==0)report(gen,oldpop);gotoxy(30,25);ttt=clock()/18.2;tt=ttt/60;printf("Run Clock: %2d: %2d: %4.2f",tt/60,tt%60,ttt-tt*60.0); printf("Min=%6.4f Nm:%d\n",min,co_min);}while((gen<maxgen)&&!bioskey(1));getch();for(k=0;k<lchrom;k++){if((k%16)==0)fprintf(fp,"\n");fprintf(fp,"%5d",oldpop[maxpp].chrom[k] ); }fprintf(fp,"\n");fclose(fp);farfree(dd);farfree(p1);farfree(oldpop);farfree(newpop);restorecrtmode();exit(0);}/*%%%%%%%%%%%%%%%%*/float objfunc(float x1){float y;y=100.0*ff/x1;}/*&&&&&&&&&&&&&&&&&&&*/void statistics(pop)struct pp *pop;{int j;sumfitness=pop[0].fitness;min=pop[0].fitness;max=pop[0].fitness;maxpp=0;minpp=0;for(j=1;j<popsize;j++){sumfitness=sumfitness+pop[j].fitness;if(pop[j].fitness>max){max=pop[j].fitness;maxpp=j;}if(pop[j].fitness<min){min=pop[j].fitness;minpp=j;}}avg=sumfitness/(float)popsize;}/*%%%%%%%%%%%%%%%%%%%%*/void generation(){unsigned int k,j,j1,j2,i1,i2,mate1,mate2;float f1,f2;j=0;do{mate1=select();pp:mate2=select();if(mate1==mate2)goto pp;crossover(oldpop[mate1].chrom,oldpop[mate2].chrom,j); newpop[j].x=(float)decode(newpop[j].chrom);newpop[j].fitness=objfunc(newpop[j].x);newpop[j].parent1=mate1;newpop[j].parent2=mate2;newpop[j].xsite=jcross;newpop[j+1].x=(float)decode(newpop[j+1].chrom);newpop[j+1].fitness=objfunc(newpop[j+1].x);newpop[j+1].parent1=mate1;newpop[j+1].parent2=mate2;newpop[j+1].xsite=jcross;if(newpop[j].fitness>min){for(k=0;k<lchrom;k++)oldpop[minpp].chrom[k]=newpop[j].chrom[k];oldpop[minpp].x=newpop[j].x;oldpop[minpp].fitness=newpop[j].fitness;co_min++;return;}if(newpop[j+1].fitness>min){for(k=0;k<lchrom;k++)oldpop[minpp].chrom[k]=newpop[j+1].chrom[k];oldpop[minpp].x=newpop[j+1].x;oldpop[minpp].fitness=newpop[j+1].fitness;co_min++;return;}j=j+2;}while(j<popsize);}/*%%%%%%%%%%%%%%%%%*/void initdata(){unsigned int ch,j;clrscr();printf("-----------------------\n");printf("A SGA\n");printf("------------------------\n");/*pause();*/clrscr();printf("*******SGA DA TA ENTRY AND INITILIZA TION *******\n"); printf("\n");printf("input pop size");scanf("%d",&popsize);printf("input chrom length");scanf("%d",&lchrom);printf("input max generations");scanf("%d",&maxgen);printf("input crossover probability");scanf("%f",&pcross);printf("input mutation prob");scanf("%f",&pmutation);randomize1();clrscr();nmutation=0;ncross=0;}/*%%%%%%%%%%%%%%%%%%%%*/void initreport(){int j,k;printf("pop size=%d\n",popsize);printf("chromosome length=%d\n",lchrom); printf("maxgen=%d\n",maxgen);printf("pmutation=%f\n",pmutation);printf("pcross=%f\n",pcross);printf("initial generation statistics\n");printf("ini pop max fitness=%f\n",max);printf("ini pop avr fitness=%f\n",avg);printf("ini pop min fitness=%f\n",min);printf("ini pop sum fit=%f\n",sumfitness);}void initpop( ){unsigned char j1;unsigned int k5,i1,i2,j,i,k,j2,j3,j4,p5[maxstring]; float f1,f2;j=0;for(k=0;k<lchrom;k++)oldpop[j].chrom[k]=k;for(k=0;k<lchrom;k++)p5[k]=oldpop[j].chrom[k];randomize();for(;j<popsize;j++){j2=random(lchrom);for(k=0;k<j2+20;k++){j3=random(lchrom);j4=random(lchrom);j1=p5[j3];p5[j3]=p5[j4];p5[j4]=j1;}for(k=0;k<lchrom;k++)oldpop[j].chrom[k]=p5[k];}for(k=0;k<lchrom;k++)for(j=0;j<lchrom;j++)dd[k*lchrom+j]=hypot(x[k]-x[j],y[k]-y[j]);for(j=0;j<popsize;j++){oldpop[j].x=(float)decode(oldpop[j].chrom); oldpop[j].fitness=objfunc(oldpop[j].x);oldpop[j].parent1=0;oldpop[j].parent2=0;oldpop[j].xsite=0;}}/*&&&&&&&&&&&&&&&&&*/void initialize(){int k,j,minx,miny,maxx,maxy;initdata();minx=0;miny=0;maxx=0;maxy=0;for(k=0;k<lchrom;k++){x[k]=rand();if(x[k]>maxx)maxx=x[k];if(x[k]<minx)minx=x[k];y[k]=rand();if(y[k]>maxy)maxy=y[k];if(y[k]<miny)miny=y[k];}if((maxx-minx)>(maxy-miny)){maxxy=maxx-minx;}else {maxxy=maxy-miny;}maxdd=0.0;for(k=0;k<lchrom;k++)for(j=0;j<lchrom;j++){dd[k*lchrom+j]=hypot(x[k]-x[j],y[k]-y[j]);if(maxdd<dd[k*lchrom+j])maxdd=dd[k*lchrom+j]; }refpd=dd[lchrom-1];for(k=0;k<lchrom;k++)refpd=refpd+dd[k*lchrom+k+2];for(j=0;j<lchrom;j++)dd[j*lchrom+j]=4.0*maxdd;ff=(0.765*maxxy*pow(lchrom,0.5));minpp=0;min=dd[lchrom-1];for(j=0;j<lchrom-1;j++){if(dd[lchrom*j+lchrom-1]<min){min=dd[lchrom*j+lchrom-1];minpp=j;}}initpop();statistics(oldpop);initreport();}/*&&&&&&&&&&&&&&&&&&*/void report(int l,struct pp *pop){int k,ix,iy,jx,jy;unsigned int tt;float ttt;cleardevice();gotoxy(1,1);printf("city:%4d para_size:%4d maxgen:%4d ref_tour:%f\n",lchrom,popsize,maxgen,refpd);printf("ncross:%4d Nmutation:%4d Rungen:%4d A VG=%8.4f MIN=%8.4f\n\n" ,ncross,nmutation,l,avg,min);printf("inpath:%6.4f Minpath length:%10.4f Ref_co_tour:%f\n",pop[maxpp].x/maxxy,pop[maxpp].x,ff);printf("Co_minpath:%6.4f Maxfit:%10.8f",100.0*pop[maxpp].x/ff,pop[maxpp].fitness);ttt=clock()/18.2;tt=ttt/60;printf("Run clock:%2d:%2d:%4d.2f\n",tt/60,tt%60,ttt-tt*60.0);setcolor(1%15+1);for(k=0;k<lchrom-1;k++){ix=x[pop[maxpp].chrom[k]];iy=y[pop[maxpp].chrom[k]]+110;jx=x[pop[maxpp].chrom[k+1]];jy=y[pop[maxpp].chrom[k+1]]+110;line(ix,iy,jx,jy);putpixel(ix,iy,RED);}ix=x[pop[maxpp].chrom[0]];iy=y[pop[maxpp].chrom[0]]+110;jx=x[pop[maxpp].chrom[lchrom-1]];jy=y[pop[maxpp].chrom[lchrom-1]]+110;line(ix,iy,jx,jy);putpixel(jx,jy,RED);setcolor(11);outtextxy(ix,iy,"*");setcolor(12);for(k=0;k<1%200;k++){ix=k+280;iy=366-fm[k]/3;jx=ix+1;jy=366-fm[k+1]/3;line(ix,iy,jx,jy);putpixel(ix,iy,RED);}printf("GEN:%3d",l);printf("Minpath:%f Maxfit:%f",pop[maxpp].x,pop[maxpp].fitness); printf("Clock:%2d:%2d:%4.2f\n",tt/60,tt%60,ttt-tt*60.0);}/*###############*/float decode(unsigned char *pp){int j,k,l;float tt;tt=dd[pp[0]*lchrom+pp[lchrom-1]];for(j=0;j<lchrom-1;j++){tt=tt+dd[pp[j]*lchrom+pp[j+1]];}l=0;for(k=0;k<lchrom-1;k++)for(j=k+1;j<lchrom;j++){if(pp[j]==pp[k])l++;}return tt+4*l*maxdd;}/*%%%%%%%%%%%%%%%%%%*/void crtinit(){int driver,mode;struct palettetype p;driver=DETECT;mode=0;initgraph(&driver,&mode,"");cleardevice();}/*$$$$$$$$$$$$$$$$$$$$*/int select(){double rand1,partsum;float r1;int j;partsum=0.0;j=0;rand1=random1()*sumfitness;do{partsum=partsum+oldpop[j].fitness;j=j+1;}while((partsum<rand1)&&(j<popsize));return j-1;}/*$$$$$$$$$$$$$$$*/int crossover(unsigned char *parent1,unsigned char *parent2,int k5) {int k,j,mutate,i1,i2,j5;int j1,j2,j3,s0,s1,s2;unsigned char jj,ts1[maxstring],ts2[maxstring];float f1,f2;s0=0;s1=0;s2=0;if(flip(pcross)){jcross=random(lchrom-1);j5=random(lchrom-1);ncross=ncross+1;if(jcross>j5){k=jcross;jcross=j5;j5=k;}}else jcross=lchrom;if(jcross!=lchrom){s0=1;k=0;for(j=jcross;j<j5;j++){ts1[k]=parent1[j];ts2[k]=parent2[j];k++;}j3=k;for(j=0;j<lchrom;j++){j2=0;while((parent2[j]!=ts1[j2])&&(j2<k)){j2++;}if(j2==k){ts1[j3]=parent2[j];j3++;}}j3=k;for(j=0;j<lchrom;j++){j2=0;while((parent1[j]!=ts2[j2])&&(j2<k)){j2++;}if(j2==k){ts2[j3]=parent1[j];j3++;}}for(j=0;j<lchrom;j++){newpop[k5].chrom[j]=ts1[j];newpop[k5+1].chrom[j]=ts2[j];}}else{for(j=0;j<lchrom;j++){newpop[k5].chrom[j]=parent1[j];newpop[k5+1].chrom[j]=parent2[j];}mutate=flip(pmutation);if(mutate){s1=1;nmutation=nmutation+1;for(j3=0;j3<200;j3++){j1=random(lchrom);j=random(lchrom);jj=newpop[k5].chrom[j];newpop[k5].chrom[j]=newpop[k5].chrom[j1]; newpop[k5].chrom[j1]=jj;}}mutate=flip(pmutation);if(mutate){s2=1;nmutation=nmutation+1;for(j3=0;j3<100;j3++){j1=random(lchrom);j=random(lchrom);jj=newpop[k5+1].chrom[j];newpop[k5+1].chrom[j]=newpop[k5+1].chrom[j1]; newpop[k5+1].chrom[j1]=jj;}}}j2=random(2*lchrom/3);for(j=j2;j<j2+lchrom/3-1;j++)for(k=0;k<lchrom;k++){if(k==j)continue;if(k>j){i2=k;i1=j;}else{i1=k;i2=j;}f1=dd[lchrom*newpop[k5].chrom[i1]+newpop[k5].chrom[i2]];f1=f1+dd[lchrom*newpop[k5].chrom[(i1+1)%lchrom]+newpop[k5].chrom[(i2+1)%lchrom]];f2=dd[lchrom*newpop[k5].chrom[i1]+newpop[k5].chrom[(i1+1)%lchrom]];f2=f2+dd[lchrom*newpop[k5].chrom[i2]+newpop[k5].chrom[(i2+1)%lchrom]];if(f1<f2){inversion(i1,i2,newpop[k5].chrom);}}j2=random(2*lchrom/3);for(j=j2;j<j2+lchrom/3-1;j++)for(k=0;k<lchrom;k++){if(k==j)continue;if(k>j){i2=k;i1=j;}else{i1=k;i2=j;}f1=dd[lchrom*newpop[k5+1].chrom[i1]+newpop[k5+1].chrom[i2]]; f1=f1+dd[lchrom*newpop[k5+1].chrom[(i1+1)%lchrom]+ newpop[k5+1].chrom[(i2+1)%lchrom]];f2=dd[lchrom*newpop[k5+1].chrom[i1]+newpop[k5+1].chrom[(i1+1)%lchrom]];f2=f2+dd[lchrom*newpop[k5+1].chrom[i2]+newpop[k5+1].chrom[(i2+1)%lchrom]];if(f1<f2){inversion(i1,i2,newpop[k5+1].chrom);}}return 1;}/*$$$$$$$$$$$$$$$*/void inversion(unsigned int k,unsigned int j,unsigned char *ss) {unsigned int l1,i;unsigned char tt;l1=(j-k)/2;for(i=0;i<l1;i++){tt=ss[k+i+1];ss[k+i+1]=ss[j-i];ss[j-i]=tt;}}/*%%%%%%%%%%%%%%%*/void randomize1(){int i;randomize();for(i=0;i<lchrom;i++)oldrand[i]=random(30001)/30000.0;jrand=0;}/*%%%%%%%%%%%*/float random1(){jrand=jrand+1;if(jrand>=lchrom){jrand=0;randomize1();}return oldrand[jrand];}/*%%%%%%%%%%*/int flip(float probability){float ppp;ppp=random(20001)/20000.0;if(ppp<=probability)return 1;return 0;}改进后用来求解VRP问题的Delphi程序:unit uEA;interfaceusesuUtilsEA, uIEA, uITSP, Classes, GaPara, windows, SysUtils, fEA_TSP;typeTIndividual = class(TInterfacedObject, IIndividual)private// The internally stored fitness valuefFitness: TFloat;fWeConstrain: integer;fBackConstrain: integer;fTimeConstrain: integer;procedure SetFitness(const V alue: TFloat);function GetFitness: TFloat;function GetWeConstrain: integer;procedure SetWeConstrain(const V alue: integer);procedure SetBackConstrain(const V alue: integer);function GetBackConstrain: integer;function GetTimeConstrain: integer;procedure SetTimeConstrain(const V alue: integer);publicproperty Fitness : TFloat read GetFitness write SetFitness;property WeConstrain :integer read GetWeConstrain write SetWeConstrain; property BackConstrain :integer read GetBackConstrain write SetBackConstrain; property TimeConstrain :integer read GetTimeConstrain write SetTimeConstrain; end;TTSPIndividual = class(TIndividual, ITSPIndividual)private// The route we travelfRouteArray : ArrayInt;fWeConstrain: integer;fBackConstrain: integer;fTimeConstrain: integer;function GetRouteArray(I: Integer): Integer;procedure SetRouteArray(I: Integer; const V alue: Integer);procedure SetSteps(const V alue: Integer);function GetSteps: Integer;function GetWeConstrain: integer;procedure SetWeConstrain(const V alue: integer);procedure SetBackConstrain(const V alue: integer);procedure SetTimeConstrain(const V alue: integer);function GetBackConstrain: integer;function GetTimeConstrain: integer;public// Constructor, called with initial route sizeconstructor Create(Size : TInt); reintroduce;destructor Destroy; override;property RouteArray[I : Integer] : Integer read GetRouteArray write SetRouteArray; // The number of steps on the routeproperty Steps : Integer read GetSteps write SetSteps;property Fitness : TFloat read GetFitness write SetFitness;property WeConstrain :integer read GetWeConstrain write SetWeConstrain; property BackConstrain :integer read GetWeConstrain write SetBackConstrain; property TimeConstrain :integer read GetTimeConstrain write SetTimeConstrain; end;TTSPCreator = class(TInterfacedObject, ITSPCreator)private// The Control component we are associated withfController: ITSPController;function GetController: ITSPController;procedure SetController(const V alue: ITSPController);public// Function to create a random individualfunction CreateIndividual : IIndividual;function CreateFeasibleIndividual: IIndividual;property Controller : ITSPController read GetController write SetController;end;TKillerPercentage = class(TInterfacedObject, IkillerPercentage)privatefPer: TFloat;procedure SetPercentage(const V alue: TFloat);function GetPercentage: TFloat;publicfunction Kill(Pop : Ipopulation ): Integer;// Percentage of population to be killedproperty Percentage: TFloat read GetPercentage write SetPercentage;end;TParentSelectorTournament = class(TInterfacedObject, IParentSelector)publicfunction SelectParent(Population: IPopulation): IIndividual;end;TTSPBreederCrossover = class(TInterfacedObject, IBreeder)publicfunction BreedOffspring(PSelector: IParentSelector; Pop: IPopulation): IIndividual; end;TTSPMutator = class(TInterfacedObject, ITSPMutator)privatefTrans: TFloat;fInv: TFloat;procedure SetInv(const V alue: TFloat);procedure SetTrans(const V alue: TFloat);function GetInv: TFloat;function GetTrans: TFloat;publicprocedure Mutate(Individual: IIndividual);published// Probability of doing a transpositionproperty Transposition: TFloat read GetTrans write SetTrans;// Probability of doing an inversionproperty Inversion: TFloat read GetInv write SetInv;end;TTSPExaminer = class(TInterfacedObject, ITSPExaminer)private// The Control component we are associated withfController: ITSPController;function GetController: ITSPController;procedure SetController(const V alue: ITSPController);public// Returns the fitness of an individual as a real number where 0 => best function GetFitness(Individual : IIndividual) : TFloat;property Controller : ITSPController read GetController write SetController; end;TPopulation = class(TInterfacedObject, IPopulation)private// The populationfPop : TInterfaceList;// Worker for breedingfBreeder: IBreeder;// Worker for killingfKiller: IKiller;// Worker for parent selectionfParentSelector: IParentSelector;// Worker for mutationfMutator: IMutator;// Worker for initial creationfCreator: ICreator;// Worker for fitness calculationfExaminer: IExaminer;// On Change eventFOnChange: TNotifyEvent;procedure Change;// Getters and Settersfunction GetIndividual(I: Integer): IIndividual;function GetCount: Integer;function GetBreeder: IBreeder;function GetCreator: ICreator;function GetExaminer: IExaminer;function GetKiller: IKiller;function GetMutator: IMutator;function GetOnChange: TNotifyEvent;function GetParentSelector: IParentSelector;procedure SetBreeder(const V alue: IBreeder);procedure SetCreator(const V alue: ICreator);procedure SetExaminer(const V alue: IExaminer);procedure SetKiller(const V alue: IKiller);procedure SetMutator(const V alue: IMutator);procedure SetOnChange(const V alue: TNotifyEvent);procedure SetParentSelector(const V alue: IParentSelector);// not interfacedprocedure DanQuickSort(SortList: TInterfaceList; L, R: Integer; SCompare: TInterfaceCompare); procedure Sort(Compare: TInterfaceCompare);protected// Comparison function for Sort()function CompareIndividuals(I1, I2: IIndividual): Integer;// Sort the populationprocedure SortPopulation;public// The constructorconstructor Create;// The destructordestructor Destroy; override;// Adds an individual to the populationprocedure Add(New : IIndividual);// Deletes an individual from the populationprocedure Delete(I : Integer);// Runs a single generationprocedure Generation;// Initialise the populationprocedure Initialise(Size : Integer);// Clear ourselves outprocedure Clear;// Get the fitness of an individualfunction FitnessOf(I : Integer) : TFloat;// Access to the population membersproperty Pop[I : Integer] : IIndividual read GetIndividual; default;// The size of the populationproperty Count : Integer read GetCount;property ParentSelector : IParentSelector read GetParentSelector write SetParentSelector; property Breeder : IBreeder read GetBreeder write SetBreeder;property Killer : IKiller read GetKiller write SetKiller;property Mutator : IMutator read GetMutator write SetMutator;property Creator : ICreator read GetCreator write SetCreator;property Examiner : IExaminer read GetExaminer write SetExaminer;// An eventproperty OnChange : TNotifyEvent read GetOnChange write SetOnChange;end;TTSPController = class(TInterfacedObject, ITSPController)privatefXmin, fXmax, fYmin, fYmax: TFloat;{ The array of 'cities' }fCities : array of TPoint2D;{ The array of 'vehicles' }fV ehicles : array of TV ehic le;{ The array of 'vehicle number' }fNoV ehic les : ArrayInt;/////////////////////{ The number of 'new cities' }fCityCount: Integer;{ The number of 'old cities' }foldCityCount: Integer;{ The number of 'travelers' }fTravelCount:Integer; ///////////////////////{ The number of 'depots' }fDepotCount:Integer; ///////////////////////{ Getters... }function GetCity(I: Integer): TPoint2D;function GetNoV ehicle(I: Integer): TInt;function GetCityCount: Integer;function GetOldCityCount: Integer;function GetTravelCount:Integer;function GetDepotCount:Integer;function GetXmax: TFloat;function GetXmin: TFloat;function GetYmax: TFloat;function GetYmin: TFloat;。

相关文档
最新文档