遗传算法java代码编写,java 遗传算法库
用java编程遗传算法怎样记录每一代的值呢?
在实例化一个数组
10多年品牌的成都网站建设公司,数千家企业网站设计经验.价格合理,可准确把握网页设计诉求.提供定制网站建设、成都做商城网站、微信小程序定制开发、成都响应式网站建设公司等服务,我们设计的作品屡获殊荣,是您值得信赖的专业网站建设公司。
没循环一次往数组里添加一个值
这样就可以了
遗传算法求最短路径
#includestdio.h
#includeiostream
#includestring.h
#includemalloc.h
#includestdlib.h
#includestring
using namespace std;
#define OVERFLOW -2
#define OK 1
#define ERROR 0
#define INFINITY 200//最大值
#define MAX_VERTEX_NUM 20//最大顶点个数
typedef char VertexType;//定义为char类型
//以下是全局变量,用于保存弗洛伊德算法的路径和长度
int D[MAX_VERTEX_NUM][MAX_VERTEX_NUM];//记录最短路径长度
int P[MAX_VERTEX_NUM][MAX_VERTEX_NUM][MAX_VERTEX_NUM];//记录最短路径标记
//以下是全局变量,用于保存迪杰斯特拉算法的路径和长度
int Distance[MAX_VERTEX_NUM];
VertexType former[MAX_VERTEX_NUM];//终点的前一个顶点
bool final[MAX_VERTEX_NUM];//记录顶点是否在V-S中
typedef struct ArcCell
{
int adj; //顶点关系类型
int weight; //该弧相关信息的指针,在此记录为权值
}ArcCell,AdjMatrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
typedef struct
{
VertexType vexs[MAX_VERTEX_NUM]; //顶点向量
AdjMatrix arcs; //邻接矩阵
int vexnum; //顶点数
int arcnum; //弧数
}MGraph;
void InitialMGraph(MGraph G)//初始化
{
G.arcnum=G.vexnum=0; //初始化边数跟顶点数都为零
for(int i=0;iMAX_VERTEX_NUM;i++)
for(int j=0;jMAX_VERTEX_NUM;j++)
{
if(i==j)
G.arcs[i][j].weight=0;
else
G.arcs[i][j].weight=INFINITY; //初始化为200,以200认为是无穷大
}
}
void InsertVex(MGraph G,VertexType v)//插入顶点
{
if(G.vexnum=MAX_VERTEX_NUM)
G.vexs[G.vexnum++]=v;
}
void InsertArc(MGraph G,VertexType v1,VertexType v2)//插入边
{
int m,n;
G.arcnum++;
for(int k=0;kG.vexnum;k++)
{
if(G.vexs[k]==v1)
m=k;
if(G.vexs[k]==v2)
n=k;
}
//插入
ArcCell A;
cout"请输入权值:";
cinA.weight;
G.arcs[m][n].weight=A.weight;
}
//迪杰斯特拉最短路径,假设始点就存储在数组中的第一个
void ShortestPath_DIJ(MGraph G,int v0)
{
//初始化距离
for(int v=0;vG.vexnum;++v)
{
final[v]=false;
Distance[v]=G.arcs[v0][v].weight;
if(Distance[v]INFINITYDistance[v]!=0)
{
former[v]=G.vexs[v0];
}
else
former[v]='#';
}
final[v0]=true;
former[v0]=G.vexs[v0];
for(int i=1;iG.vexnum;++i)//剩余的G.vexnum-1个顶点
{
int w;
int min=INFINITY;
int v=-1;
for(w=0;wG.vexnum;++w)
{
if(!final[w]Distance[w]min)
{
v=w;
min=Distance[w];
}
}
if(v!=-1)
{
final[v]=true;//将离顶点V0最近的顶点v加入S集合中
for(w=0;wG.vexnum;++w)//更新当前的最短路径及距离
{
if(!final[w](min+G.arcs[v][w].weightDistance[w])G.arcs[v][w].weightINFINITY)
{
Distance[w]=min+G.arcs[v][w].weight;
former[w]=G.vexs[v];
}
}
}
}
}
//输出迪杰斯特拉中的最短路径
void output_ShortestPath_DIJ(MGraph G,int v0)
{
int i;
for(i=1;iG.vexnum;i++)
{
coutG.vexs[v0]"-"G.vexs[i]":";
if(Distance[i]!=INFINITY)
{
cout"最短路径长度为:"Distance[i]" 最短路径的前一个顶点为:"former[i];
coutendl;
}
else
cout"此两顶点之间不存在路径"endl;
}
}
//弗洛伊德最短路径
void shortestPath_FLOYD(MGraph G)
{
for(int v=0;vG.vexnum;++v)
{
for(int w=0;wG.vexnum;++w)
{
D[v][w]=G.arcs[v][w].weight;
for (int k=0;k G.vexnum;k++)
P[v][w][k]=-1;
if(D[v][w]INFINITY) //从v到w有直接路径
P[v][w][v]=w;
}
}
for(int k=0;kG.vexnum;++k)
{
for(int v=0;vG.vexnum;v++)
for(int w=0;wG.vexnum;++w)
if(D[v][w]D[v][k]+D[k][w])
{
D[v][w]=D[v][k]+D[k][w];
for(int i=0;iG.vexnum;i++)
{
if(P[v][k][i]!=-1)//原来存了顶点
P[v][w][i]=P[v][k][i];
else
P[v][w][i]=P[k][w][i];
}
}
}
}
//输出弗洛伊德中的最短路径
void output_shortestPath_FLOYD(MGraph G)
{
for(int i=0;iG.vexnum;++i)
{
for(int j=0;jG.vexnum;++j)
{
if(i!=j)//自己不能到达自己
{
coutG.vexs[i]"-"G.vexs[j]":";
if(D[i][j]==INFINITY)
{
cout"此两顶点之间不存在路径"endl;
}
else
{
cout"最短路径长度为:"" "D[i][j]" ";
cout"最短路径为:";
coutG.vexs[i];
for(int k=i;k!=-1;k=P[i][j][k])
{
if(k!=i)
coutG.vexs[k];
}
coutendl;
}
}
}
}
}
int main()
{
int num1;//顶点个数
int num2;//弧个数
cout"请输入顶点个数:";
cinnum1;
cout"请输入弧个数:";
cinnum2;
VertexType v;
MGraph G;
InitialMGraph(G);
cout"请输入顶点的信息:"endl;
for(int i=0;inum1;++i)
{
cinv;;
InsertVex(G,v);
}
VertexType v1,v2;
for(int j=0;jnum2;++j)
{
cout"请输入两个结点数据来表示的边:";
cinv1v2;
InsertArc(G,v1,v2);
}
ShortestPath_DIJ(G,0);
cout"迪杰斯特拉中的最短路径如下:"endl;
output_ShortestPath_DIJ(G,0);
coutendlendl;
shortestPath_FLOYD(G);
cout"弗洛伊德中的最短路径如下:"endl;
output_shortestPath_FLOYD(G);
return 0;
}
急求 遗传算法 java程序
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/**
* 编写者: 赖志环
* 标准遗传算法求解函数
* 编写日期: 2007-12-2
*/
class Best {
public int generations; //最佳适应值代号
public String str; //最佳染色体
public double fitness; //最佳适应值
}
public class SGAFrame extends JFrame {
private JTextArea textArea;
private String str = "";
private Best best = null; //最佳染色体
private String[] ipop = new String[10]; //染色体
private int gernation = 0; //染色体代号
public static final int GENE = 22; //基因数
/**
* Launch the application
* @param args
*/
public static void main(String args[]) {
try {
SGAFrame frame = new SGAFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the frame
*/
public SGAFrame() {
super();
this.ipop = inialPops();
getContentPane().setLayout(null);
setBounds(100, 100, 461, 277);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JLabel label = new JLabel();
label.setText("X的区间:");
label.setBounds(23, 10, 88, 15);
getContentPane().add(label);
final JLabel label_1 = new JLabel();
label_1.setText("[-255,255]");
label_1.setBounds(92, 10, 84, 15);
getContentPane().add(label_1);
final JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
SGAFrame s = new SGAFrame();
str = str + s.process() + "\n";
textArea.setText(str);
}
});
button.setText("求最小值");
button.setBounds(323, 27, 99, 23);
getContentPane().add(button);
final JLabel label_2 = new JLabel();
label_2.setText("利用标准遗传算法求解函数f(x)=(x-5)*(x-5)的最小值:");
label_2.setBounds(23, 31, 318, 15);
getContentPane().add(label_2);
final JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBounds(23, 65, 399, 164);
getContentPane().add(panel);
final JScrollPane scrollPane = new JScrollPane();
panel.add(scrollPane, BorderLayout.CENTER);
textArea = new JTextArea();
scrollPane.setViewportView(textArea);
//
}
/**
* 初始化一条染色体(用二进制字符串表示)
* @return 一条染色体
*/
private String inialPop() {
String res = "";
for (int i = 0; i GENE; i++) {
if (Math.random() 0.5) {
res += "0";
} else {
res += "1";
}
}
return res;
}
/**
* 初始化一组染色体
* @return 染色体组
*/
private String[] inialPops() {
String[] ipop = new String[10];
for (int i = 0; i 10; i++) {
ipop[i] = inialPop();
}
return ipop;
}
/**
* 将染色体转换成x的值
* @param str 染色体
* @return 染色体的适应值
*/
private double calculatefitnessvalue(String str) {
int b = Integer.parseInt(str, 2);
//String str1 = "" + "/n";
double x = -255 + b * (255 - (-255)) / (Math.pow(2, GENE) - 1);
//System.out.println("X = " + x);
double fitness = -(x - 5) * (x - 5);
//System.out.println("f(x)=" + fitness);
//str1 = str1 + "X=" + x + "/n"
//+ "f(x)=" + "fitness" + "/n";
//textArea.setText(str1);
return fitness;
}
/**
* 计算群体上每个个体的适应度值;
* 按由个体适应度值所决定的某个规则选择将进入下一代的个体;
*/
private void select() {
double evals[] = new double[10]; // 所有染色体适应值
double p[] = new double[10]; // 各染色体选择概率
double q[] = new double[10]; // 累计概率
double F = 0; // 累计适应值总和
for (int i = 0; i 10; i++) {
evals[i] = calculatefitnessvalue(ipop[i]);
if (best == null) {
best = new Best();
best.fitness = evals[i];
best.generations = 0;
best.str = ipop[i];
} else {
if (evals[i] best.fitness) // 最好的记录下来
{
best.fitness = evals[i];
best.generations = gernation;
best.str = ipop[i];
}
}
F = F + evals[i]; // 所有染色体适应值总和
}
for (int i = 0; i 10; i++) {
p[i] = evals[i] / F;
if (i == 0)
q[i] = p[i];
else {
q[i] = q[i - 1] + p[i];
}
}
for (int i = 0; i 10; i++) {
double r = Math.random();
if (r = q[0]) {
ipop[i] = ipop[0];
} else {
for (int j = 1; j 10; j++) {
if (r q[j]) {
ipop[i] = ipop[j];
break;
}
}
}
}
}
/**
* 交叉操作
* 交叉率为25%,平均为25%的染色体进行交叉
*/
private void cross() {
String temp1, temp2;
for (int i = 0; i 10; i++) {
if (Math.random() 0.25) {
double r = Math.random();
int pos = (int) (Math.round(r * 1000)) % GENE;
if (pos == 0) {
pos = 1;
}
temp1 = ipop[i].substring(0, pos)
+ ipop[(i + 1) % 10].substring(pos);
temp2 = ipop[(i + 1) % 10].substring(0, pos)
+ ipop[i].substring(pos);
ipop[i] = temp1;
ipop[(i + 1) / 10] = temp2;
}
}
}
/**
* 基因突变操作
* 1%基因变异m*pop_size 共180个基因,为了使每个基因都有相同机会发生变异,
* 需要产生[1--180]上均匀分布的
*/
private void mutation() {
for (int i = 0; i 4; i++) {
int num = (int) (Math.random() * GENE * 10 + 1);
int chromosomeNum = (int) (num / GENE) + 1; // 染色体号
int mutationNum = num - (chromosomeNum - 1) * GENE; // 基因号
if (mutationNum == 0)
mutationNum = 1;
chromosomeNum = chromosomeNum - 1;
if (chromosomeNum = 10)
chromosomeNum = 9;
//System.out.println("变异前" + ipop[chromosomeNum]);
String temp;
if (ipop[chromosomeNum].charAt(mutationNum - 1) == '0') {
if (mutationNum == 1) {
temp = "1" + ipop[chromosomeNum].substring
(mutationNum);
} else {
if (mutationNum != GENE) {
temp = ipop[chromosomeNum].substring(0, mutationNum -
1) + "1" + ipop
[chromosomeNum].substring(mutationNum);
} else {
temp = ipop[chromosomeNum].substring(0, mutationNum -
1) + "1";
}
}
} else {
if (mutationNum == 1) {
temp = "0" + ipop[chromosomeNum].substring
(mutationNum);
} else {
if (mutationNum != GENE) {
temp = ipop[chromosomeNum].substring(0, mutationNum -
1) + "0" + ipop
[chromosomeNum].substring(mutationNum);
} else {
temp = ipop[chromosomeNum].substring(0, mutationNum -
1) + "1";
}
}
}
ipop[chromosomeNum] = temp;
//System.out.println("变异后" + ipop[chromosomeNum]);
}
}
/**
* 执行遗传算法
*/
public String process() {
String str = "";
for (int i = 0; i 10000; i++) {
this.select();
this.cross();
this.mutation();
gernation = i;
}
str = "最小值" + best.fitness + ",第" + best.generations + "个染色体";
return str;
}
}
如何用Java实现遗传算法?
通过遗传算法走迷宫。虽然图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();
}
}
求《Java遗传算法编程》全文免费下载百度网盘资源,谢谢~
《Java遗传算法编程》百度网盘pdf最新全集下载:
链接:
?pwd=xv3v 提取码: xv3v
简介:本书简单、直接地介绍了遗传算法,并且针对所讨论的示例问题,给出了Java代码的算法实现。全书分为6章。第1章简单介绍了人工智能和生物进化的知识背景,这也是遗传算法的历史知识背景。第2章给出了一个基本遗传算法的实现;第4章和第5章,分别针对机器人控制器、旅行商问题、排课问题展开分析和讨论,并给出了算法实现。在这些章的末尾,还给出了一些练习供读者深入学习和实践。第6章专门讨论了各种算法的优化问题。
使用java来实现在智能组卷中的遗传算法(急急急)
题目好像是让你做个增强版的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代码编写,java 遗传算法库
分享网址:http://azwzsj.com/article/hcdepo.html