當前位置:首頁 » 操作系統 » 遺傳演算法java實現

遺傳演算法java實現

發布時間: 2022-05-21 07:32:52

java寫的遺傳演算法

package baseclass;
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 + "個染色體"+best.str;
return str;
}

}

Ⅱ java實驗 遺傳演算法

你好,我以前從csdn上下過一個源代碼,不過沒試過怎麼用,給你參考一下:

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

要是有點c基礎的話可以看看c++ primer 看看前幾章的容器和泛型演算法 用這個實現遺傳演算法解決旅行商問題 代碼100行左右

Ⅳ 用JAVA實現遺傳演算法求最小值的問題,一直報錯,如下: 應該是越界拋的異常,如何解決呢

具體遺傳演算法我沒研究過,但是這個異常是數組下標越界引起的,數組里沒有數據,你去索引了第一個,肯定是哪裡不細心了,如果邏輯沒問題的話,在這一行(GeneticAlgorithmMin.java:102)加個判斷,數組長度為0就不索引,這樣就不會報錯。 不過我估計涉及到邏輯性的其他地方了,就算不報錯,程序也會有邏輯性問題,你給的資料不夠,我盡力了

Ⅳ java中有沒有專門為遺傳演算法等智能演算法設計的包呢

JGAP(Java Genetic Algorithms Package -- Java遺傳演算法包)

Ⅵ 《Java遺傳演算法編程》pdf下載在線閱讀全文,求百度網盤雲資源

《Java遺傳演算法編程》網路網盤pdf最新全集下載:
鏈接: https://pan..com/s/1l6_14X1Yhcgv8kYwHqyY2g

?pwd=xv3v 提取碼: xv3v
簡介:本書簡單、直接地介紹了遺傳演算法,並且針對所討論的示例問題,給出了Java代碼的演算法實現。全書分為6章。第1章簡單介紹了人工智慧和生物進化的知識背景,這也是遺傳演算法的歷史知識背景。第2章給出了一個基本遺傳演算法的實現;第4章和第5章,分別針對機器人控制器、旅行商問題、排課問題展開分析和討論,並給出了演算法實現。在這些章的末尾,還給出了一些練習供讀者深入學習和實踐。第6章專門討論了各種演算法的優化問題。

Ⅶ 如何用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程序

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程序實現的就太太完美了,

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實現多目標遺傳演算法的代碼

給分吧,我給你發一段。

熱點內容
演算法製造 發布:2024-10-25 23:11:27 瀏覽:885
台式電腦安裝哪個安卓系統好 發布:2024-10-25 23:11:25 瀏覽:113
怎麼樣學電腦編程 發布:2024-10-25 23:10:13 瀏覽:523
安卓手機內存佔用太多如何清理 發布:2024-10-25 23:03:53 瀏覽:909
swift項目編譯 發布:2024-10-25 22:53:12 瀏覽:962
邁銳寶買哪個配置合算 發布:2024-10-25 22:28:59 瀏覽:993
押韻腳本生成器 發布:2024-10-25 22:26:50 瀏覽:368
找文檔上傳 發布:2024-10-25 22:22:29 瀏覽:875
hibernate使用二級緩存 發布:2024-10-25 22:14:00 瀏覽:359
手機版登陸布穀鳥伺服器地址 發布:2024-10-25 22:13:59 瀏覽:173