导航:首页 > 编程语言 > java遗传算法代码

java遗传算法代码

发布时间:2023-01-03 03:57:30

‘壹’ 遗传算法的模拟 数据结构题目

我这里给出了一个简单的模板如果需要编代码填代码的地方已经有提示了
/*package otherFile;

import java.util.Random;
import tGraph.TdcppGraph;
import shuffP.*;
*/
/**************
*
* @author vaqeteart
* 这里是遗传算法的核心框架遗传算法的步骤:
* 遗传算法核心部分的算法描述
* 算法步骤:
* 1、初始化
* 1.1、生成初始种群编码
* 1.2、计算每个个体的适配值。
* 1.3、记录当前最优适配值和最优个体
* 2、选择和遗传,
* 2.0、若当前最优适配值多次小于已有的最优适配值(或相差不大)很多次,或者进化的次数超过设定的限制,转4。
* 2.1、按照与每个个体的适配值成正比的概率选择个体并复制,复制之后个体的数目和原始种群数目一样。
* 2.2、(最好先打乱复制后种群的个体次序)对复制后个体进行两两配对交叉,生成相同数目的的下一代种群。
* 2.3、对下一代种群按照一定的概率进行变异
* 2.4、计算每个个体的适配值。
* 2.5、记录当前最优适配值和最优个体
* 2.6、转2
* 3、返回当前最优适配值以及其对应的编码,结束。
*
* 注意:
* 1.这里的内容相当于一个模板,编写具体的遗传算法的时候,可以按照这个模板的形式编写。
* 2.应该填写代码的地方都有提示的标记。
*/

public class GAKernel
{
//number of population
int popNum;//set the number to 20 in constructor
//current evolution times
int evolutionTim;
//limit of the evolution times
int evolutionLim;//set the number to 20 in constructor
//unaccepted times
//int eliminTim;
//limit of unaccepted times
//int eliminLim;
//current best euler code
//int curBestCode[];
//current best fitness
int curBestFitness;
//fitness of every indivial
int iFitness[];
//fator of compute the fitness
int factor;
//..................other members.............................................

//the graph
//public TdcppGraph tpGraph;
//the eula code group
//int codes[][];
//every population
//
//constructor
GAKernel(TdcppGraph tG,int eulerCode[])
{
popNum = 32;//2*2*2*2*2
//factor = Integer.MAX_VALUE / popNum;//to avoid overflow when select,for every fitness
evolutionTim = 0;/////
evolutionLim = 15;///////
//this.tpGraph=new TdcppGraph(tG);
//eliminTim = 0;
//eliminLim
curBestFitness = 0;
//curBestCode = new int[eulerCode.length];
//for(int i = 0; i < curBestCode.length; ++i)
//{
// curBestCode[i] = eulerCode[i];
//}
//??curBestFitness
iFitness = new int[popNum];
//codes = new int[popNum][];//lines
for(int i = 0; i < popNum; ++i)
{
//codes[i] = new int[eulerCode.length];
iFitness[i] = 0;
}
System.out.println("构造函数,需要填入代码");
}
//initialize the originalpopulation
void initPopulation()
{
//.......................初始化种群........................................
//int tmpCode[] = new int[curBestCode.length];
//get the initial indivial
//for(int i = 0; i < curBestCode.length; ++i)
//{
// tmpCode[i] = curBestCode[i];
// codes[0][i] = tmpCode[i];
//}
//ShuffEP s = new ShuffEP(this.tpGraph);
//for(int i = 1; i < popNum; ++i)
//{
// s.shuff(tmpCode);
// for(int j = 0; j < tmpCode.length; ++j)
// {
// codes[i][j] = tmpCode[j];
// }
//}
System.out.println("初始化种群,需要填入代码");
//get the initial fitness to the member iFitness
computeFitness();
//get the initial best indivial and fitness
recordBest();
}
//compute the fitness of every indivial in current population
void computeFitness()
{
//........................计算每个个体适应度.......................
//int time = 0;
//for(int i = 0; i < popNum; ++i)
//{
// time = 0;
// for(int j = 0; j < codes[i].length - 1; ++j)
// {
// time += tpGraph.Edge(codes[i][j], codes[i][j + 1]).getCost(time);
// }
// iFitness[i] = factor - time;
// if(iFitness[i] < 0)
// {
// System.out.println("错误,某个个体适应度过小使得适配值出现负数");//lkdebug
// System.exit(1);
// }
//}
System.out.println("计算每个个体适应度,需要填入代码");
}
//record the current best fitness and the according indivial
void recordBest()
{
int bestIndex = -1;
for(int i = 0; i < popNum; ++i)
{
if(curBestFitness < iFitness[i])
{
curBestFitness = iFitness[i];
bestIndex = i;
}
}
//............................记录最优个体.............................
if(bestIndex > -1)
{
// for(int i = 0; i < curBestCode.length; ++i)
// {
// curBestCode[i] = codes[bestIndex][i];
// }
}
System.out.println("记录最优个体,需要填入代码");
}
//selection and reproce indivial in population
void selIndivial()
{
int tmpiFitness[] = new int[iFitness.length];
tmpiFitness[0] = iFitness[0];
//建立临时群体用于选择交换
//.................................复制个体...............................
//清除原来的群体
//int tmpCode[][] = new int[popNum][];
//for(int i = 0; i < codes.length; ++i)
//{
// tmpCode[i] = new int[codes[i].length];//???
// for(int j = 0; j < codes[i].length; ++j)
// {// to tmpCode and reset codes
// tmpCode[i][j] = codes[i][j];
// codes[i][j] = -1;
// }
//}
System.out.println("复制个体,需要填入代码");
for(int i = 1; i < tmpiFitness.length; ++i)
{
tmpiFitness[i] = tmpiFitness[i - 1] + iFitness[i];
//iFitness[i] = 0;
}
//轮盘赌选择个体
for(int i = 0; i < popNum; ++i)
{
int rFit = new Random().nextInt(tmpiFitness[tmpiFitness.length - 1]);
for(int j = 0; j < tmpiFitness.length; ++j)
{
if(rFit < tmpiFitness[j])
{
rFit = j;//record the index of the indivial
break;
}
}
if(rFit == 0)
{
iFitness[i] = tmpiFitness[rFit];
}
else
{
iFitness[i] = tmpiFitness[rFit] - tmpiFitness[rFit - 1];// fitness
}
//....................................选择个体...........................
//for(int j = 0; j < tmpCode[rFit].length; ++j)
//{
// codes[i][j] =tmpCode[rFit][j];
//}
System.out.println("选择个体,需要填入代码");
}
//get the copied fitness in iFitness
}
//match every two indivial and cross the code
void matchCross()
{
//........................需要填入代码................................
System.out.println("配对交叉,需要填入代码");
}
//mutate by a specifical probability
void mutate()
{
//........................按照一定的概率进行变异.......................
System.out.println("按照一定的概率进行变异,需要填入代码");
}
//evolve current population
void evolve()
{
selIndivial();
matchCross();
mutate();
}
//compute the approximative best value by GA
//find approximative best solution by GA
public void compute()
{
initPopulation();
//while((evolutionTim < evolutionLim) && (eliminTim < eliminLim))
while(evolutionTim < evolutionLim)
{
evolve();
//get the initial fitness to the member iFitness
computeFitness();
//get the initial best indivial and fitness
recordBest();
++evolutionTim;
}
}
}

‘贰’ 用JAVA实现遗传算法求最小值的问题,一直报错,如下: 应该是越界抛的异常,如何解决呢

具体遗传算法我没研究过,但是这个异常是数组下标越界引起的,数组里没有数据,你去索引了第一个,肯定是哪里不细心了,如果逻辑没问题的话,在这一行(GeneticAlgorithmMin.java:102)加个判断,数组长度为0就不索引,这样就不会报错。 不过我估计涉及到逻辑性的其他地方了,就算不报错,程序也会有逻辑性问题,你给的资料不够,我尽力了

‘叁’ 《Java遗传算法编程pdf下载在线阅读全文,求百度网盘云资源

《Java遗传算法编程》网络网盘pdf最新全集下载:
链接: https://pan..com/s/1l6_14X1Yhcgv8kYwHqyY2g

?pwd=xv3v 提取码: xv3v
简介:本书简单、直接地介绍了遗传算法,并且针对所讨论的示例问题,给出了Java代码的算法实现。全书分为6章。第1章简单介绍了人工智能和生物进化的知识背景,这也是遗传算法的历史知识背景。第2章给出了一个基本遗传算法的实现;第4章和第5章,分别针对机器人控制器、旅行商问题、排课问题展开分析和讨论,并给出了算法实现。在这些章的末尾,还给出了一些练习供读者深入学习和实践。第6章专门讨论了各种算法的优化问题。

‘肆’ 使用java来实现在智能组卷中的遗传算法(急急急)

题目好像是让你做个增强版的List ,简单的都实现了 程序架子大概是这样,排序查找什么的网络搜下 算法很多,套着每样写个方法就行了,测试就在main‘方法里写

publicclassMyList{
privateString[]arr;
privateintcount;
publicMyList(intcount){
arr=newString[count];
this.count=count;
}
publicMyList(int[]intArr){
arr=newString[intArr.length];
this.count=intArr.length;
for(inti=0;i<intArr.length;i++){
arr[i]=intArr[i]+"";
}
}

publicMyList(String[]stringArr){
arr=stringArr;
this.count=stringArr.length;
}
publicintgetLength(){
returncount;
}
//清空容器内的数组。
publicvoidclearAll(){
arr=newString[count];
}
//通过给定元素下标来删除某一元素
publicvoidremoveBySeqn(intseqn){
if(seqn>=0&&seqn<count){
arr[seqn]=null;
}
}
publicstaticvoidmain(String[]args){
MyListlist=newMyList(40);
MyListlist1=newMyList({3,2,125,56,123});
MyListlist2=newMyList({"123",""ad});
list2.removeBySeqn(0);
list1.clearAll();
}
}

‘伍’ 用java编程遗传算法怎样记录每一代的值呢

在实例化一个数组
没循环一次往数组里添加一个值
这样就可以了

‘陆’ 遗传算法代码出错

函数minwucha(a,b,c)的参数改为长度为3的向量,如minwucha(p),p为长度为3的向量。

‘柒’ 求基于遗传算法的多目标优化代码 用C,C++或java实现。最好能够运行

好高深

‘捌’ 急求java代码:遗传算法解决车辆路径问题。。

把这个地址的程序http://..com/question/340500887.html 中,这一句public void print(){
改成public void print(){}加一个大括号就可以运行了。

‘玖’ 如何用Java实现遗传算法

通过遗传算法走迷宫。虽然图1和图2均成功走出迷宫,但是图1比图2的路径长的多,且复杂,遗传算法可以计算出有多少种可能性,并选择其中最简洁的作为运算结果。

示例图1:

实现代码:

importjava.util.ArrayList;

importjava.util.Collections;

importjava.util.Iterator;

importjava.util.LinkedList;

importjava.util.List;

importjava.util.Random;

/**

* 用遗传算法走迷宫

*

* @author Orisun

*

*/

publicclassGA {

intgene_len;// 基因长度

intchrom_len;// 染色体长度

intpopulation;// 种群大小

doublecross_ratio;// 交叉率

doublemuta_ratio;// 变异率

intiter_limit;// 最多进化的代数

List<boolean[]> indivials;// 存储当代种群的染色体

Labyrinth labyrinth;

intwidth;//迷宫一行有多少个格子

intheight;//迷宫有多少行

publicclassBI {

doublefitness;

boolean[] indv;

publicBI(doublef,boolean[] ind) {

fitness = f;

indv = ind;

}

publicdoublegetFitness() {

returnfitness;

}

publicboolean[] getIndv() {

returnindv;

}

}

List<BI> best_indivial;// 存储每一代中最优秀的个体

publicGA(Labyrinth labyrinth) {

this.labyrinth=labyrinth;

this.width = labyrinth.map[0].length;

this.height = labyrinth.map.length;

chrom_len =4* (width+height);

gene_len =2;

population =20;

cross_ratio =0.83;

muta_ratio =0.002;

iter_limit =300;

indivials =newArrayList<boolean[]>(population);

best_indivial =newArrayList<BI>(iter_limit);

}

publicintgetWidth() {

returnwidth;

}

publicvoidsetWidth(intwidth) {

this.width = width;

}

publicdoublegetCross_ratio() {

returncross_ratio;

}

publicList<BI> getBest_indivial() {

returnbest_indivial;

}

publicLabyrinth getLabyrinth() {

returnlabyrinth;

}

publicvoidsetLabyrinth(Labyrinth labyrinth) {

this.labyrinth = labyrinth;

}

publicvoidsetChrom_len(intchrom_len) {

this.chrom_len = chrom_len;

}

publicvoidsetPopulation(intpopulation) {

this.population = population;

}

publicvoidsetCross_ratio(doublecross_ratio) {

this.cross_ratio = cross_ratio;

}

publicvoidsetMuta_ratio(doublemuta_ratio) {

this.muta_ratio = muta_ratio;

}

publicvoidsetIter_limit(intiter_limit) {

this.iter_limit = iter_limit;

}

// 初始化种群

publicvoidinitPopulation() {

Random r =newRandom(System.currentTimeMillis());

for(inti =0; i < population; i++) {

intlen = gene_len * chrom_len;

boolean[] ind =newboolean[len];

for(intj =0; j < len; j++)

ind[j] = r.nextBoolean();

indivials.add(ind);

}

}

// 交叉

publicvoidcross(boolean[] arr1,boolean[] arr2) {

Random r =newRandom(System.currentTimeMillis());

intlength = arr1.length;

intslice =0;

do{

slice = r.nextInt(length);

}while(slice ==0);

if(slice < length /2) {

for(inti =0; i < slice; i++) {

booleantmp = arr1[i];

arr1[i] = arr2[i];

arr2[i] = tmp;

}

}else{

for(inti = slice; i < length; i++) {

booleantmp = arr1[i];

arr1[i] = arr2[i];

arr2[i] = tmp;

}

}

}

// 变异

publicvoidmutation(boolean[] indivial) {

intlength = indivial.length;

Random r =newRandom(System.currentTimeMillis());

indivial[r.nextInt(length)] ^=false;

}

// 轮盘法选择下一代,并返回当代最高的适应度值

publicdoubleselection() {

boolean[][] next_generation =newboolean[population][];// 下一代

intlength = gene_len * chrom_len;

for(inti =0; i < population; i++)

next_generation[i] =newboolean[length];

double[] cumulation =newdouble[population];

intbest_index =0;

doublemax_fitness = getFitness(indivials.get(best_index));

cumulation[0] = max_fitness;

for(inti =1; i < population; i++) {

doublefit = getFitness(indivials.get(i));

cumulation[i] = cumulation[i -1] + fit;

// 寻找当代的最优个体

if(fit > max_fitness) {

best_index = i;

max_fitness = fit;

}

}

Random rand =newRandom(System.currentTimeMillis());

for(inti =0; i < population; i++)

next_generation[i] = indivials.get(findByHalf(cumulation,

rand.nextDouble() * cumulation[population -1]));

// 把当代的最优个体及其适应度放到best_indivial中

BI bi =newBI(max_fitness, indivials.get(best_index));

// printPath(indivials.get(best_index));

//System.out.println(max_fitness);

best_indivial.add(bi);

// 新一代作为当前代

for(inti =0; i < population; i++)

indivials.set(i, next_generation[i]);

returnmax_fitness;

}

// 折半查找

publicintfindByHalf(double[] arr,doublefind) {

if(find <0|| find ==0|| find > arr[arr.length -1])

return-1;

intmin =0;

intmax = arr.length -1;

intmedium = min;

do{

if(medium == (min + max) /2)

break;

medium = (min + max) /2;

if(arr[medium] < find)

min = medium;

elseif(arr[medium] > find)

max = medium;

else

returnmedium;

}while(min < max);

returnmax;

}

// 计算适应度

publicdoublegetFitness(boolean[] indivial) {

intlength = indivial.length;

// 记录当前的位置,入口点是(1,0)

intx =1;

inty =0;

// 根据染色体中基因的指导向前走

for(inti =0; i < length; i++) {

booleanb1 = indivial[i];

booleanb2 = indivial[++i];

// 00向左走

if(b1 ==false&& b2 ==false) {

if(x >0&& labyrinth.map[y][x -1] ==true) {

x--;

}

}

// 01向右走

elseif(b1 ==false&& b2 ==true) {

if(x +1< width && labyrinth.map[y][x +1] ==true) {

x++;

}

}

// 10向上走

elseif(b1 ==true&& b2 ==false) {

if(y >0&& labyrinth.map[y -1][x] ==true) {

y--;

}

}

// 11向下走

elseif(b1 ==true&& b2 ==true) {

if(y +1< height && labyrinth.map[y +1][x] ==true) {

y++;

}

}

}

intn = Math.abs(x - labyrinth.x_end) + Math.abs(y -labyrinth.y_end) +1;

// if(n==1)

// printPath(indivial);

return1.0/ n;

}

// 运行遗传算法

publicbooleanrun() {

// 初始化种群

initPopulation();

Random rand =newRandom(System.currentTimeMillis());

booleansuccess =false;

while(iter_limit-- >0) {

// 打乱种群的顺序

Collections.shuffle(indivials);

for(inti =0; i < population -1; i +=2) {

// 交叉

if(rand.nextDouble() < cross_ratio) {

cross(indivials.get(i), indivials.get(i +1));

}

// 变异

if(rand.nextDouble() < muta_ratio) {

mutation(indivials.get(i));

}

}

// 种群更替

if(selection() ==1) {

success =true;

break;

}

}

returnsuccess;

}

// public static void main(String[] args) {

// GA ga = new GA(8, 8);

// if (!ga.run()) {

// System.out.println("没有找到走出迷宫的路径.");

// } else {

// int gen = ga.best_indivial.size();

// boolean[] indivial = ga.best_indivial.get(gen - 1).indv;

// System.out.println(ga.getPath(indivial));

// }

// }

// 根据染色体打印走法

publicString getPath(boolean[] indivial) {

intlength = indivial.length;

intx =1;

inty =0;

LinkedList<String> stack=newLinkedList<String>();

for(inti =0; i < length; i++) {

booleanb1 = indivial[i];

booleanb2 = indivial[++i];

if(b1 ==false&& b2 ==false) {

if(x >0&& labyrinth.map[y][x -1] ==true) {

x--;

if(!stack.isEmpty() && stack.peek()=="右")

stack.poll();

else

stack.push("左");

}

}elseif(b1 ==false&& b2 ==true) {

if(x +1< width && labyrinth.map[y][x +1] ==true) {

x++;

if(!stack.isEmpty() && stack.peek()=="左")

stack.poll();

else

stack.push("右");

}

}elseif(b1 ==true&& b2 ==false) {

if(y >0&& labyrinth.map[y -1][x] ==true) {

y--;

if(!stack.isEmpty() && stack.peek()=="下")

stack.poll();

else

stack.push("上");

}

}elseif(b1 ==true&& b2 ==true) {

if(y +1< height && labyrinth.map[y +1][x] ==true) {

y++;

if(!stack.isEmpty() && stack.peek()=="上")

stack.poll();

else

stack.push("下");

}

}

}

StringBuilder sb=newStringBuilder(length/4);

Iterator<String> iter=stack.descendingIterator();

while(iter.hasNext())

sb.append(iter.next());

returnsb.toString();

}

}

‘拾’ 急求java 遗传算法实现排课功能(控制台程序)的代码

关于交叉的疑问,不就是父亲和母亲随机位上的基因进行交换得到孩子的基因,后面一句”然后选择所有基因位上的数总和最大的染色体C1“就不明白了。

阅读全文

与java遗传算法代码相关的资料

热点内容
dvd光盘存储汉子算法 浏览:757
苹果邮件无法连接服务器地址 浏览:962
phpffmpeg转码 浏览:671
长沙好玩的解压项目 浏览:142
专属学情分析报告是什么app 浏览:564
php工程部署 浏览:833
android全屏透明 浏览:736
阿里云服务器已开通怎么办 浏览:803
光遇为什么登录时服务器已满 浏览:302
PDF分析 浏览:484
h3c光纤全工半全工设置命令 浏览:143
公司法pdf下载 浏览:381
linuxmarkdown 浏览:350
华为手机怎么多选文件夹 浏览:683
如何取消命令方块指令 浏览:349
风翼app为什么进不去了 浏览:778
im4java压缩图片 浏览:362
数据查询网站源码 浏览:150
伊克塞尔文档怎么进行加密 浏览:892
app转账是什么 浏览:163