Java遗传算法之冲出迷宫
程序员文章站
2024-02-27 22:47:09
遗传算法是模拟达尔文生物进化论的自然选择和遗传学机理的生物进化过程的计算模型,是一种通过模拟自然进化过程搜索最优解的方法。它能解决很多问题,比如数学方程的最大最小值,背包问...
遗传算法是模拟达尔文生物进化论的自然选择和遗传学机理的生物进化过程的计算模型,是一种通过模拟自然进化过程搜索最优解的方法。它能解决很多问题,比如数学方程的最大最小值,背包问题,装箱问题等。在游戏开发中遗传算法的应用也十分频繁,不少的游戏 ai 都利用遗传算法进行编码。
就个人理解,遗传算法是模拟神奇的大自然中生物“优胜劣汰”原则指导下的进化过程,好的基因有更多的机会得到繁衍,这样一来,随着繁衍的进行,生物种群会朝着一个趋势收敛。而生物繁衍过程中的基因杂交和变异会给种群提供更好的基因序列,这样种群的繁衍趋势将会是“长江后浪推前浪,一代更比一代强”,而不会是只受限于祖先的最好基因。而程序可以通过模拟这种过程来获得问题的最优解(但不一定能得到)。要利用该过程来解决问题,受限需要构造初始的基因组,并为对每个基因进行适应性分数(衡量该基因的好坏程度)初始化,接着从初始的基因组中选出两个父基因(根据适应性分数,采用轮盘算法进行选择)进行繁衍,基于一定的杂交率(父基因进行杂交的概率)和变异率(子基因变异的概率),这两个父基因会生成两个子基因,然后将这两个基因放入种群中,到这里繁衍一代完成,重复繁衍的过程直到种群收敛或适应性分数达到最大。
接下来我们就看看用遗传算法冲出迷宫的实例。
代码如下:
import java.awt.color; import java.awt.graphics; import java.awt.gridlayout; import java.util.arraylist; import java.util.list; import java.util.random; import javax.swing.jframe; import javax.swing.jlabel; import javax.swing.jpanel; @suppresswarnings("serial") public class mazeproblem extends jframe{ //当前基因组 private static list<gene> genegroup = new arraylist<>(); private static random random = new random(); private static int startx = 2; private static int starty = 0; private static int endx = 7; private static int endy = 14; //杂交率 private static final double crossover_rate = 0.7; //变异率 private static final double mutation_rate = 0.0001; //基因组初始个数 private static final int pop_size = 140; //基因长度 private static final int chromo_length = 70; //最大适应性分数的基因 private static gene maxgene = new gene(chromo_length); //迷宫地图 private static int[][] map = {{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,0,1,0,0,0,0,0,1,1,1,0,0,0,1}, {5,0,0,0,0,0,0,0,1,1,1,0,0,0,1}, {1,0,0,0,1,1,1,0,0,1,0,0,0,0,1}, {1,0,0,0,1,1,1,0,0,0,0,0,1,0,1}, {1,1,0,0,1,1,1,0,0,0,0,0,1,0,1}, {1,0,0,0,0,1,0,0,0,0,1,1,1,0,1}, {1,0,1,1,0,0,0,1,0,0,0,0,0,0,8}, {1,0,1,1,0,0,0,1,0,0,0,0,0,0,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}}; private static int map_width = 15; private static int map_height = 10; private list<jlabel> labels = new arraylist<>(); public mazeproblem(){ // 初始化 setsize(700, 700); setdefaultcloseoperation(dispose_on_close); setresizable(false); getcontentpane().setlayout(null); jpanel panel = new jpanel(); panel.setlayout(new gridlayout(map_height,map_width)); panel.setbounds(10, 10, map_width*40, map_height*40); getcontentpane().add(panel); for(int i=0;i<map_height;i++){ for(int j=0;j<map_width;j++){ jlabel label = new jlabel(); color color = null; if(map[i][j] == 1){ color = color.black; } if(map[i][j] == 0){ color = color.gray; } if(map[i][j] == 5 || map[i][j] ==8){ color = color.red; } label.setbackground(color); label.setopaque(true); panel.add(label); labels.add(label); } } } @override public void paint(graphics g) { super.paint(g); //画出路径 int[] gene = maxgene.getgene(); int curx = startx; int cury = starty; for(int i=0;i<gene.length;i+=2){ //上 if(gene[i] == 0 && gene[i+1] == 0){ if(curx >=1 && map[curx-1][cury] == 0){ curx --; } } //下 else if(gene[i] == 0 && gene[i+1] == 1){ if(curx <=map_height-1 && map[curx+1][cury] == 0){ curx ++; } } //左 else if(gene[i] == 1 && gene[i+1] == 0){ if(cury >=1 && map[curx][cury-1] == 0){ cury --; } } //右 else{ if(cury <= map_width-1 && map[curx][cury+1] == 0){ cury ++; } } labels.get(curx*map_width+cury).setbackground(color.blue); } } public static void main(string[] args) { //初始化基因组 init(); while(maxgene.getscore() < 1){ //选择进行交配的两个基因 int p1 = getparent(genegroup); int p2 = getparent(genegroup); //用轮盘转动法选择两个基因进行交配,杂交和变异 mate(p1,p2); } new mazeproblem().setvisible(true); } /** * 根据路径获得适应性分数 * @param path * @return */ private static double getscore(int[] gene){ double result = 0; int curx = startx; int cury = starty; for(int i=0;i<gene.length;i+=2){ //上 if(gene[i] == 0 && gene[i+1] == 0){ if(curx >=1 && map[curx-1][cury] == 0){ curx --; } } //下 else if(gene[i] == 0 && gene[i+1] == 1){ if(curx <=map_height-1 && map[curx+1][cury] == 0){ curx ++; } } //左 else if(gene[i] == 1 && gene[i+1] == 0){ if(cury >=1 && map[curx][cury-1] == 0){ cury --; } } //右 else{ if(cury <= map_width-1 && map[curx][cury+1] == 0){ cury ++; } } } double x = math.abs(curx - endx); double y = math.abs(cury - endy); //如果和终点只有一格距离则返回1 if((x == 1&& y==0) || (x==0&&y==1)){ return 1; } //计算适应性分数 result = 1/(x+y+1); return result; } /** * 基因初始化 */ private static void init(){ for(int i=0;i<pop_size;i++){ gene gene = new gene(chromo_length); double score = getscore(gene.getgene()); if(score > maxgene.getscore()){ maxgene = gene; } gene.setscore(score); genegroup.add(gene); } } /** * 根据适应性分数随机获得进行交配的父类基因下标 * @param list * @return */ private static int getparent(list<gene> list){ int result = 0; double r = random.nextdouble(); double score; double sum = 0; double totalscores = gettotalscores(genegroup); for(int i=0;i<list.size();i++){ gene gene = list.get(i); score = gene.getscore(); sum += score/totalscores; if(sum >= r){ result = i; return result; } } return result; } /** * 获得全部基因组的适应性分数总和 * @param list * @return */ private static double gettotalscores(list<gene> list){ double result = 0; for(int i=0;i<list.size();i++){ result += list.get(i).getscore(); } return result; } /** * 两个基因进行交配 * @param p1 * @param p2 */ private static void mate(int n1,int n2){ gene p1 = genegroup.get(n1); gene p2 = genegroup.get(n2); gene c1 = new gene(chromo_length); gene c2 = new gene(chromo_length); int[] gene1 = new int[chromo_length]; int[] gene2 = new int[chromo_length]; for(int i=0;i<chromo_length;i++){ gene1[i] = p1.getgene()[i]; gene2[i] = p2.getgene()[i]; } //先根据杂交率决定是否进行杂交 double r = random.nextdouble(); if(r >= crossover_rate){ //决定杂交起点 int n = random.nextint(chromo_length); for(int i=n;i<chromo_length;i++){ int tmp = gene1[i]; gene1[i] = gene2[i]; gene2[i] = tmp; } } //根据变异率决定是否 r = random.nextdouble(); if(r >= mutation_rate){ //选择变异位置 int n = random.nextint(chromo_length); if(gene1[n] == 0){ gene1[n] = 1; } else{ gene1[n] = 0; } if(gene2[n] == 0){ gene2[n] = 1; } else{ gene2[n] = 0; } } c1.setgene(gene1); c2.setgene(gene2); double score1 = getscore(c1.getgene()); double score2 = getscore(c2.getgene()); if(score1 >maxgene.getscore()){ maxgene = c1; } if(score2 >maxgene.getscore()){ maxgene = c2; } c1.setscore(score1); c2.setscore(score2); genegroup.add(c1); genegroup.add(c2); } } /** * 基因 * @author zzf * */ class gene{ //染色体长度 private int len; //基因数组 private int[] gene; //适应性分数 private double score; public gene(int len){ this.len = len; gene = new int[len]; random random = new random(); //随机生成一个基因序列 for(int i=0;i<len;i++){ gene[i] = random.nextint(2); } //适应性分数设置为0 this.score = 0; } public int getlen() { return len; } public void setlen(int len) { this.len = len; } public int[] getgene() { return gene; } public void setgene(int[] gene) { this.gene = gene; } public double getscore() { return score; } public void setscore(double score) { this.score = score; } public void print(){ stringbuilder sb = new stringbuilder(); for(int i=0;i<gene.length;i+=2){ if(gene[i] == 0 && gene[i+1] == 0){ sb.append("上"); } //下 else if(gene[i] == 0 && gene[i+1] == 1){ sb.append("下"); } //左 else if(gene[i] == 1 && gene[i+1] == 0){ sb.append("左"); } //右 else{ sb.append("右"); } } system.out.println(sb.tostring()); } }
以上就是本文关于遗传算法冲出迷宫方法实例解析,希望对大家有所帮助。