java实现遗传算法实例分享(打印城市信息)

代码如下:

import java.util.*;
public class Tsp { 
    private String cityName[]={"北京","上海","天津","重庆","哈尔滨","长春","沈阳","呼和浩特","石家庄","太原","济南","郑州","西安","兰州","银川","西宁","乌鲁木齐","合肥","南京","杭州","长沙","南昌","武汉","成都","贵州","福建","台北","广州","海口","南宁","昆明","拉萨","香港","澳门"};
    //private String cityEnd[]=new String[34];
    private int cityNum=cityName.length;     //城市个数
    private int popSize = 50;               //种群数量
    private int maxgens = 20000;            //迭代次数
    private double pxover = 0.8;            //交叉概率
    private double pmultation = 0.05;       //变异概率
    private long[][] distance = new long[cityNum][cityNum];
    private int range = 2000;               //用于判断何时停止的数组区间
    private class genotype {
        int city[] = new int[cityNum];      //单个基因的城市序列
        long fitness;                      //该基因的适应度
        double selectP;                        //选择概率
        double exceptp;                        //期望概率
        int isSelected;                        //是否被选择
    }
    private genotype[] citys = new genotype[popSize];
    /**
     *    构造函数,初始化种群
     */
    public Tsp() {
        for (int i = 0; i < popSize; i++) {
            citys[i] = new genotype();
            int[] num = new int[cityNum];
            for (int j = 0; j < cityNum; j++)
                num[j] = j;
            int temp = cityNum;
            for (int j = 0; j < cityNum; j++) {
                int r = (int) (Math.random() * temp);
                citys[i].city[j] = num[r];
                num[r] = num[temp - 1];
                temp--;
            }
            citys[i].fitness = 0;
            citys[i].selectP = 0;
            citys[i].exceptp = 0;
            citys[i].isSelected = 0;
        }
        initDistance();
    }
    /**
     *  计算每个种群每个基因个体的适应度,选择概率,期望概率,和是否被选择。
     */
    public void CalAll(){
        for( int i = 0; i< popSize; i++){
            citys[i].fitness = 0;
            citys[i].selectP = 0;
            citys[i].exceptp = 0;
            citys[i].isSelected = 0;
        }
        CalFitness();
        CalSelectP();
        CalExceptP();
        CalIsSelected();
    }
    /**
     *    填充,将多选的填充到未选的个体当中
     */
    public void pad(){
        int best = 0;
        int bad = 0;
        while(true){          
            while(citys[best].isSelected <= 1 && best<popSize-1)
                best ++;
            while(citys[bad].isSelected != 0 && bad<popSize-1)
                bad ++;
            for(int i = 0; i< cityNum; i++)
                citys[bad].city[i] = citys[best].city[i];
                citys[best].isSelected --;
                citys[bad].isSelected ++;
                bad ++;  
            if(best == popSize ||bad == popSize)
                break;
        }
    }
    /**
     *    交叉主体函数
     */
    public void crossover() {
        int x;
        int y;
        int pop = (int)(popSize* pxover /2);
        while(pop>0){
            x = (int)(Math.random()*popSize);
            y = (int)(Math.random()*popSize);
            executeCrossover(x,y);//x y 两个体执行交叉
            pop--;
        }
    }
    /**
     * 执行交叉函数
     * @param 个体x
     * @param 个体y
     * 对个体x和个体y执行佳点集的交叉,从而产生下一代城市序列
     */
    private void executeCrossover(int x,int y){
        int dimension = 0;
        for( int i = 0 ;i < cityNum; i++)
            if(citys[x].city[i] != citys[y].city[i]){
                dimension ++;
            } 
        int diffItem = 0;
        double[] diff = new double[dimension];
        for( int i = 0 ;i < cityNum; i++){
            if(citys[x].city[i] != citys[y].city[i]){
                diff[diffItem] = citys[x].city[i];
                citys[x].city[i] = -1;
                citys[y].city[i] = -1;
                diffItem ++;
            } 
        }
        Arrays.sort(diff);
        double[] temp = new double[dimension];
        temp = gp(x, dimension);
        for( int k = 0; k< dimension;k++)
            for( int j = 0; j< dimension; j++)
                if(temp[j] == k){
                    double item = temp[k];
                    temp[k] = temp[j];
                    temp[j] = item;
                    item = diff[k];
                    diff[k] = diff[j];
                    diff[j] = item; 
                }
        int tempDimension = dimension;
        int tempi = 0;
        while(tempDimension> 0 ){
            if(citys[x].city[tempi] == -1){
                citys[x].city[tempi] = (int)diff[dimension - tempDimension];
                tempDimension --;
            } 
            tempi ++;
        }
        Arrays.sort(diff);
        temp = gp(y, dimension);
        for( int k = 0; k< dimension;k++)
            for( int j = 0; j< dimension; j++)
                if(temp[j] == k){
                    double item = temp[k];
                    temp[k] = temp[j];
                    temp[j] = item;
                    item = diff[k];
                    diff[k] = diff[j];
                    diff[j] = item; 
                }
        tempDimension = dimension;
        tempi = 0;
        while(tempDimension> 0 ){
            if(citys[y].city[tempi] == -1){
                citys[y].city[tempi] = (int)diff[dimension - tempDimension];
                tempDimension --;
            } 
            tempi ++;
        }
    }
    /**
     * @param individual 个体
     * @param dimension    维数
     * @return 佳点集   (用于交叉函数的交叉点)    在executeCrossover()函数中使用
     */
    private double[] gp(int individual, int dimension){
        double[] temp = new double[dimension];
        double[] temp1 = new double[dimension];
        int p = 2 * dimension + 3;
        while(!isSushu(p))
            p++;
        for( int i = 0; i< dimension; i++){
            temp[i] = 2*Math.cos(2*Math.PI*(i+1)/p) * (individual+1);
            temp[i] = temp[i] - (int)temp[i];
            if( temp [i]< 0)
                temp[i] = 1+temp[i];
        }
        for( int i = 0; i< dimension; i++)
            temp1[i] = temp[i];
        Arrays.sort(temp1);
        //排序
        for( int i = 0; i< dimension; i++)
            for( int j = 0; j< dimension; j++)
                if(temp[j]==temp1[i])
                    temp[j] = i;
        return temp;
    }
    /**
     *    变异
     */
    public void mutate(){
        double random;
        int temp;
        int temp1;
        int temp2;
        for( int i = 0 ; i< popSize; i++){
            random = Math.random();
            if(random<=pmultation){
                temp1 = (int)(Math.random() * (cityNum));
                temp2 = (int)(Math.random() * (cityNum));
                temp = citys[i].city[temp1];
                citys[i].city[temp1] = citys[i].city[temp2];
                citys[i].city[temp2] = temp;
            }
        }     
    }
    /**
     * 打印当前代数的所有城市序列,以及其相关的参数
     */
    public void print(){
    /**
     * 初始化各城市之间的距离
     */
    private void initDistance(){
        for (int i = 0; i < cityNum; i++) {
            for (int j = 0; j < cityNum; j++){
                distance[i][j] = Math.abs(i-j);
            }
        }
    }
    /**
     * 计算所有城市序列的适应度
     */
    private void CalFitness() {
        for (int i = 0; i < popSize; i++) {
            for (int j = 0; j < cityNum - 1; j++)
                citys[i].fitness += distance[citys[i].city[j]][citys[i].city[j + 1]];
            citys[i].fitness += distance[citys[i].city[0]][citys[i].city[cityNum - 1]];
        }
    }
    /**
     * 计算选择概率
     */
    private void CalSelectP(){
        long sum = 0;
        for( int i = 0; i< popSize; i++)
            sum += citys[i].fitness;
        for( int i = 0; i< popSize; i++)
            citys[i].selectP = (double)citys[i].fitness/sum;
    }
    /**
     * 计算期望概率
     */
    private void CalExceptP(){
        for( int i = 0; i< popSize; i++)
            citys[i].exceptp = (double)citys[i].selectP * popSize;
    }
    /**
     * 计算该城市序列是否较优,较优则被选择,进入下一代
     */
    private void CalIsSelected(){
        int needSelecte = popSize;
        for( int i = 0; i< popSize; i++)
            if( citys[i].exceptp<1){
                citys[i].isSelected++;
                needSelecte --;
            }
        double[] temp = new double[popSize];
        for (int i = 0; i < popSize; i++) {
//          temp[i] = citys[i].exceptp - (int) citys[i].exceptp;
//          temp[i] *= 10;
            temp[i] = citys[i].exceptp*10;
        }
        int j = 0;
        while (needSelecte != 0) {
            for (int i = 0; i < popSize; i++) {
                if ((int) temp[i] == j) {
                    citys[i].isSelected++;
                    needSelecte--;
                    if (needSelecte == 0)
                        break;
                }
            }
            j++;
        }
    }
    /**
     * @param x
     * @return 判断一个数是否是素数的函数
     */
    private boolean isSushu( int x){
           if(x<2) return false;
           for(int i=2;i<=x/2;i++)
           if(x%i==0&&x!=2) return false;
           return true;
        }
    /**
     * @param x 数组
     * @return x数组的值是否全部相等,相等则表示x.length代的最优结果相同,则算法结束
     */
    private boolean isSame(long[] x){
        for( int i = 0; i< x.length -1; i++)
            if(x[i] !=x[i+1])
                return false;
        return true;
    }
    /**
     * 打印任意代最优的路径序列
     */
    private void printBestRoute(){
        CalAll();
        long temp = citys[0].fitness;
        int index = 0;
        for (int i = 1; i < popSize; i++) {
            if(citys[i].fitness<temp){
                temp = citys[i].fitness;
                index = i;
            }
        }
        System.out.println();
        System.out.println("最佳路径的序列:");
        for (int j = 0; j < cityNum; j++)
        {
            String cityEnd[]={cityName[citys[index].city[j]]};
            for(int m=0;m<cityEnd.length;m++)
            {
                System.out.print(cityEnd[m] + " ");
            }
        }
            //System.out.print(citys[index].city[j] + cityName[citys[index].city[j]] + "  ");
            //System.out.print(cityName[citys[index].city[j]]);
        System.out.println();
    }
    /**
     * 算法执行
     */
    public void run(){
        long[] result = new long[range];
        //result初始化为所有的数字都不相等
        for( int i  = 0; i< range; i++)
            result[i] = i;
        int index = 0;       //数组中的位置
        int num = 1;     //第num代
        while(maxgens>0){
            System.out.println("-----------------  第  "+num+" 代  -------------------------");
            CalAll();
            print();
            pad();
            crossover();
            mutate();
            maxgens --;
            long temp = citys[0].fitness;
            for ( int i = 1; i< popSize; i++)
                if(citys[i].fitness<temp){
                    temp = citys[i].fitness;
                }
            System.out.println("最优的解:"+temp);
            result[index] = temp;
            if(isSame(result))
                break;
            index++;
            if(index==range)
                index = 0;
            num++;
        }
        printBestRoute();
    }
    /**
     * @param a 开始时间
     * @param b   结束时间
     */
    public void CalTime(Calendar a,Calendar b){
        long x = b.getTimeInMillis() - a.getTimeInMillis();
        long y = x/1000;
        x = x - 1000*y;
        System.out.println("算法执行时间:"+y+"."+x+" 秒");
    }
    /**
     *    程序入口
     */
    public static void main(String[] args) {
        Calendar a = Calendar.getInstance(); //开始时间
        Tsp tsp = new Tsp();
        tsp.run();
        Calendar b = Calendar.getInstance(); //结束时间
        tsp.CalTime(a, b);
    }
}

(0)

相关推荐

  • java打印正弦曲线示例

    复制代码 代码如下: /* * 绘制0°到360°的正弦曲线 * 分两种情形,y>0和y<=0进行绘制 * 每种情形中要考虑每行打印两个"*"字符 * 并在打印第二个"*"字符后换行 */package hundred;import java.lang.Math;public class SinTest {    public static void main(String[] args){     //y为列方向,值从1到-1,步长为0.1     f

  • java打印当前方法名示例分享

    在C与C++中可以这样打印当前函数名: 复制代码 代码如下: printf("%s",__func__); 但在Java没有此说法,一切即对象,得从某个对象中去获取,可分为两种方式: 第一种:通过Thread类来获取. 复制代码 代码如下: System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName());System.out.println(Thread.currentThread().getS

  • Java打印和打印预览机制实例代码

    复制代码 代码如下: import java.awt.BasicStroke;import java.awt.BorderLayout;import java.awt.Color;import java.awt.Component;import java.awt.Dimension;import java.awt.Font;import java.awt.FontMetrics;import java.awt.Graphics;import java.awt.Graphics2D;import

  • JavaWeb实现打印功能

    废话不多说了,直接给大家贴代码了,具体代码如下所示: <script language="javascript"> function printsetup(){ // 打印页面设置 wb.execwb(8,1); } </script> </head> <body> <OBJECT classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2" height=0 id=w

  • java控制Pdf自动打印的小例子

    复制代码 代码如下: public byte[] autoPrintPdf(byte[] pdf_byte) { ByteArrayOutputStream bos=null;  try {   PdfReader reader = new PdfReader(pdf_byte);   bos = new ByteArrayOutputStream();   PdfStamper ps = new PdfStamper(reader, bos);   StringBuffer script =

  • java实现遗传算法实例分享(打印城市信息)

    复制代码 代码如下: import java.util.*;public class Tsp {      private String cityName[]={"北京","上海","天津","重庆","哈尔滨","长春","沈阳","呼和浩特","石家庄","太原","济南","

  • Java Servlet简单实例分享(文件上传下载demo)

    项目结构 src com servletdemo DownloadServlet.java ShowServlet.java UploadServlet.java WebContent jsp servlet download.html fileupload.jsp input.jsp WEB-INF lib commons-fileupload-1.3.1.jar commons-io-2.4.jar 1.简单实例 ShowServlet.java package com.servletdem

  • Java读写Excel实例分享

    话不多说,请看代码: ExcelUtil.java package pers.kangxu.datautils.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.

  • Java反射机制实例代码分享

    本文旨在对Java反射机制有一个全面的介绍,希望通过本文,大家会对Java反射的相关内容有一个全面的了解. 阅读本文之前,大家可先行参阅<重新理解Java泛型>. 前言 Java反射机制是一个非常强大的功能,在很多大型项目比如Spring, Mybatis都可以看见反射的身影.通过反射机制我们可以在运行期间获取对象的类型信息,利用这一特性我们可以实现工厂模式和代理模式等设计模式,同时也可以解决Java泛型擦除等令人苦恼的问题.本文我们就从实际应用的角度出发,来应用一下Java的反射机制. 反射

  • java图片添加水印实例代码分享

    本文为大家介绍了java图片添加水印实例代码,java实现水印还是非常方便的,水印可以是图片或者文字,具体内容如下 package michael.io.image; import java.awt.AlphaComposite; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io

  • java过滤html标签获取纯文本信息的实例

    如下所示: package com.lyt.base.util; import java.util.regex.Pattern; public class FilterHtmlUtil { public static String Html2Text(String inputString){ String htmlStr = inputString; //含html标签的字符串 String textStr =""; java.util.regex.Pattern p_script;

  • jupyter notebook tensorflow打印device信息实例

    juypter notebook中直接使用log_device_placement=True打印不出来device信息 # Creates a graph. with tf.device('/device:CPU:0'): a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a') b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name

  • Java生产1-100的随机数简单实例(分享)

    直接调用Math里面的random即可,简单方便 int i = (int)(Math.random()*100+1); 以上这篇Java生产1-100的随机数简单实例(分享)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们.

  • Java编程BigDecimal用法实例分享

    Java中提供了大数字(超过16位有效位)的操作类,即 java.math.BinInteger 类和 java.math.BigDecimal 类,用于高精度计算. 其中 BigInteger 类是针对大整数的处理类,而 BigDecimal 类则是针对大小数的处理类. BigDecimal 类的实现用到了 BigInteger类,不同的是 BigDecimal 加入了小数的概念. float和Double只能用来做科学计算或者是工程计算;在商业计算中,对数字精度要求较高,必须使用 BigIn

  • 通过Java压缩JavaScript代码实例分享

    通过移除空行和注释来压缩 JavaScript 代码 /** * This file is part of the Echo Web Application Framework (hereinafter \"Echo\"). * Copyright (C) 2002-2009 NextApp, Inc. * * Compresses a String containing JavaScript by removing comments and whitespace. */ public

随机推荐