资源描述:
《GA遗传算法C代码.doc》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、usingSystem;usingSystem.IO;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Data.OleDb;namespaceConsoleApplication1{publicclassGenetic_Algorithm{Randomrand=newRandom();intMaxTime;//最大运行时间intpopsize;
2、//种群数量intChromosomeLength;//染色体长度doubleCrossRate;//交叉率doubleMutateRate;//变异率double[]f;//适应度值int[]selected;//定义selected数组,用于表示需要进行交叉操作的染色体序号double[]wheel;//轮盘int[,]pregeneration;//上一代int[,]nextgeneration;//下一代int[]Best;//定义当前最优解intconvergence;//定义当前最优解的已持续代数int[,]timeconstrait;p
3、ublicGenetic_Algorithm(intpopulationsize,intchromolength)//GA--构造函数,变量初始化{rand=newRandom(System.DateTime.Now.Millisecond);MaxTime=50;popsize=populationsize;ChromosomeLength=chromolength;CrossRate=0.8;MutateRate=0.2;f=newdouble[2*popsize];selected=newint[popsize];wheel=newdouble
4、[popsize+1];pregeneration=newint[popsize,ChromosomeLength];//当前的染色体种群nextgeneration=newint[popsize,ChromosomeLength];//下一代(子代)染色体种群Best=newint[ChromosomeLength];convergence=1;timeconstrait=newint[20,2]{{2,6},{1,2},{3,4},{1,4},{4,7},{3,5},{2,6},{3,5},{1,4},{3,7},{5,7},{2,7},{2,4
5、},{4,5},{2,5},{4,6},{3,5},{1,4},{1,5},{3,6}};}publicvoidRunGA()//运行{inti;CreateFirstPop();//产生初始种群i=0;boolquit=true;while(quit){for(;i6、ct();//此步确定了selected[i]的值CreateNextGeneration();//产生子代,包括被选择为selected[i]的染色体的交叉,还有变异ProduceNext();}Console.WriteLine("Press'q'toquit,pressEntertocontinue.....");if(Console.Read()=='q'){quit=false;}else{MaxTime+=50;}}}voidCreateFirstPop()//产生初始种群{Console.WriteLine("Creatingfirst
7、generation..........");inti,j,r;for(i=0;i8、的染色体进行交叉,产生的子代放在pregeneration中i和i+1的位置}Mutation(refnex