重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
我这里给出了一个简单的模板如果需要编代码填代码的地方已经有提示了
为余干等地区用户提供了全套网页设计制作服务,及余干网站建设行业解决方案。主营业务为网站建设、成都网站制作、余干网站设计,以传统方式定制建设网站,并提供域名空间备案等一条龙服务,秉承以专业、用心的态度为用户提供真诚的服务。我们深信只要达到每一位用户的要求,就会得到认可,从而选择与我们长期合作。这样,我们也可以走得更远!
/*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 individual
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 individual
//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 individual and fitness
recordBest();
}
//compute the fitness of every individual 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 individual
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 reproduce individual in population
void selIndividual()
{
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)
// {//copy 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 individual
break;
}
}
if(rFit == 0)
{
iFitness[i] = tmpiFitness[rFit];
}
else
{
iFitness[i] = tmpiFitness[rFit] - tmpiFitness[rFit - 1];//copy 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 individual and cross the code
void matchCross()
{
//........................需要填入代码................................
System.out.println("配对交叉,需要填入代码");
}
//mutate by a specifical probability
void mutate()
{
//........................按照一定的概率进行变异.......................
System.out.println("按照一定的概率进行变异,需要填入代码");
}
//evolve current population
void evolve()
{
selIndividual();
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 individual and fitness
recordBest();
++evolutionTim;
}
}
}
把这个地址的程序 中,这一句public void print(){
改成public void print(){}加一个大括号就可以运行了。
在实例化一个数组
没循环一次往数组里添加一个值
这样就可以了
题目好像是让你做个增强版的List ,简单的都实现了 程序架子大概是这样,排序查找什么的百度搜下 算法很多,套着每样写个方法就行了,测试就在main‘方法里写
public class MyList {
private String[] arr;
private int count ;
public MyList (int count){
arr = new String[count];
this.count = count;
}
public MyList (int[] intArr){
arr = new String[intArr.length];
this.count = intArr.length;
for(int i=0;iintArr.length;i++){
arr[i] = intArr[i]+"";
}
}
public MyList (String[] stringArr){
arr = stringArr;
this.count = stringArr.length;
}
public int getLength(){
return count;
}
//清空容器内的数组。
public void clearAll(){
arr = new String[count];
}
//通过给定元素下标来删除某一元素
public void removeBySeqn(int seqn){
if(seqn = 0 seqncount){
arr[seqn] = null;
}
}
public static void main(String[] args){
MyList list = new MyList (40);
MyList list1 = new MyList ({3,2,125,56,123});
MyList list2 = new MyList ({"123",""ad});
list2.removeBySeqn(0);
list1.clearAll();
}
}
《Java遗传算法编程》百度网盘pdf最新全集下载:
链接:
?pwd=xv3v 提取码: xv3v
简介:本书简单、直接地介绍了遗传算法,并且针对所讨论的示例问题,给出了Java代码的算法实现。全书分为6章。第1章简单介绍了人工智能和生物进化的知识背景,这也是遗传算法的历史知识背景。第2章给出了一个基本遗传算法的实现;第4章和第5章,分别针对机器人控制器、旅行商问题、排课问题展开分析和讨论,并给出了算法实现。在这些章的末尾,还给出了一些练习供读者深入学习和实践。第6章专门讨论了各种算法的优化问题。
通过遗传算法走迷宫。虽然图1和图2均成功走出迷宫,但是图1比图2的路径长的多,且复杂,遗传算法可以计算出有多少种可能性,并选择其中最简洁的作为运算结果。
示例图1:
示例图2:
实现代码:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
/**
* 用遗传算法走迷宫
*
* @author Orisun
*
*/
public class GA {
int gene_len; // 基因长度
int chrom_len; // 染色体长度
int population; // 种群大小
double cross_ratio; // 交叉率
double muta_ratio; // 变异率
int iter_limit; // 最多进化的代数
Listboolean[] individuals; // 存储当代种群的染色体
Labyrinth labyrinth;
int width; //迷宫一行有多少个格子
int height; //迷宫有多少行
public class BI {
double fitness;
boolean[] indv;
public BI(double f, boolean[] ind) {
fitness = f;
indv = ind;
}
public double getFitness() {
return fitness;
}
public boolean[] getIndv() {
return indv;
}
}
ListBI best_individual; // 存储每一代中最优秀的个体
public GA(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;
individuals = new ArrayListboolean[](population);
best_individual = new ArrayListBI(iter_limit);
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public double getCross_ratio() {
return cross_ratio;
}
public ListBI getBest_individual() {
return best_individual;
}
public Labyrinth getLabyrinth() {
return labyrinth;
}
public void setLabyrinth(Labyrinth labyrinth) {
this.labyrinth = labyrinth;
}
public void setChrom_len(int chrom_len) {
this.chrom_len = chrom_len;
}
public void setPopulation(int population) {
this.population = population;
}
public void setCross_ratio(double cross_ratio) {
this.cross_ratio = cross_ratio;
}
public void setMuta_ratio(double muta_ratio) {
this.muta_ratio = muta_ratio;
}
public void setIter_limit(int iter_limit) {
this.iter_limit = iter_limit;
}
// 初始化种群
public void initPopulation() {
Random r = new Random(System.currentTimeMillis());
for (int i = 0; i population; i++) {
int len = gene_len * chrom_len;
boolean[] ind = new boolean[len];
for (int j = 0; j len; j++)
ind[j] = r.nextBoolean();
individuals.add(ind);
}
}
// 交叉
public void cross(boolean[] arr1, boolean[] arr2) {
Random r = new Random(System.currentTimeMillis());
int length = arr1.length;
int slice = 0;
do {
slice = r.nextInt(length);
} while (slice == 0);
if (slice length / 2) {
for (int i = 0; i slice; i++) {
boolean tmp = arr1[i];
arr1[i] = arr2[i];
arr2[i] = tmp;
}
} else {
for (int i = slice; i length; i++) {
boolean tmp = arr1[i];
arr1[i] = arr2[i];
arr2[i] = tmp;
}
}
}
// 变异
public void mutation(boolean[] individual) {
int length = individual.length;
Random r = new Random(System.currentTimeMillis());
individual[r.nextInt(length)] ^= false;
}
// 轮盘法选择下一代,并返回当代最高的适应度值
public double selection() {
boolean[][] next_generation = new boolean[population][]; // 下一代
int length = gene_len * chrom_len;
for (int i = 0; i population; i++)
next_generation[i] = new boolean[length];
double[] cumulation = new double[population];
int best_index = 0;
double max_fitness = getFitness(individuals.get(best_index));
cumulation[0] = max_fitness;
for (int i = 1; i population; i++) {
double fit = getFitness(individuals.get(i));
cumulation[i] = cumulation[i - 1] + fit;
// 寻找当代的最优个体
if (fit max_fitness) {
best_index = i;
max_fitness = fit;
}
}
Random rand = new Random(System.currentTimeMillis());
for (int i = 0; i population; i++)
next_generation[i] = individuals.get(findByHalf(cumulation,
rand.nextDouble() * cumulation[population - 1]));
// 把当代的最优个体及其适应度放到best_individual中
BI bi = new BI(max_fitness, individuals.get(best_index));
// printPath(individuals.get(best_index));
//System.out.println(max_fitness);
best_individual.add(bi);
// 新一代作为当前代
for (int i = 0; i population; i++)
individuals.set(i, next_generation[i]);
return max_fitness;
}
// 折半查找
public int findByHalf(double[] arr, double find) {
if (find 0 || find == 0 || find arr[arr.length - 1])
return -1;
int min = 0;
int max = arr.length - 1;
int medium = min;
do {
if (medium == (min + max) / 2)
break;
medium = (min + max) / 2;
if (arr[medium] find)
min = medium;
else if (arr[medium] find)
max = medium;
else
return medium;
} while (min max);
return max;
}
// 计算适应度
public double getFitness(boolean[] individual) {
int length = individual.length;
// 记录当前的位置,入口点是(1,0)
int x = 1;
int y = 0;
// 根据染色体中基因的指导向前走
for (int i = 0; i length; i++) {
boolean b1 = individual[i];
boolean b2 = individual[++i];
// 00向左走
if (b1 == false b2 == false) {
if (x 0 labyrinth.map[y][x - 1] == true) {
x--;
}
}
// 01向右走
else if (b1 == false b2 == true) {
if (x + 1 width labyrinth.map[y][x + 1] == true) {
x++;
}
}
// 10向上走
else if (b1 == true b2 == false) {
if (y 0 labyrinth.map[y - 1][x] == true) {
y--;
}
}
// 11向下走
else if (b1 == true b2 == true) {
if (y + 1 height labyrinth.map[y + 1][x] == true) {
y++;
}
}
}
int n = Math.abs(x - labyrinth.x_end) + Math.abs(y -labyrinth.y_end) + 1;
// if(n==1)
// printPath(individual);
return 1.0 / n;
}
// 运行遗传算法
public boolean run() {
// 初始化种群
initPopulation();
Random rand = new Random(System.currentTimeMillis());
boolean success = false;
while (iter_limit-- 0) {
// 打乱种群的顺序
Collections.shuffle(individuals);
for (int i = 0; i population - 1; i += 2) {
// 交叉
if (rand.nextDouble() cross_ratio) {
cross(individuals.get(i), individuals.get(i + 1));
}
// 变异
if (rand.nextDouble() muta_ratio) {
mutation(individuals.get(i));
}
}
// 种群更替
if (selection() == 1) {
success = true;
break;
}
}
return success;
}
// public static void main(String[] args) {
// GA ga = new GA(8, 8);
// if (!ga.run()) {
// System.out.println("没有找到走出迷宫的路径.");
// } else {
// int gen = ga.best_individual.size();
// boolean[] individual = ga.best_individual.get(gen - 1).indv;
// System.out.println(ga.getPath(individual));
// }
// }
// 根据染色体打印走法
public String getPath(boolean[] individual) {
int length = individual.length;
int x = 1;
int y = 0;
LinkedListString stack=new LinkedListString();
for (int i = 0; i length; i++) {
boolean b1 = individual[i];
boolean b2 = individual[++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("左");
}
} else if (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("右");
}
} else if (b1 == true b2 == false) {
if (y 0 labyrinth.map[y - 1][x] == true) {
y--;
if(!stack.isEmpty() stack.peek()=="下")
stack.poll();
else
stack.push("上");
}
} else if (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=new StringBuilder(length/4);
IteratorString iter=stack.descendingIterator();
while(iter.hasNext())
sb.append(iter.next());
return sb.toString();
}
}