整理资料搬运——退火算法Annealing的Java实现

直接上代码:

package sa;

import java.util.ArrayList;
import java.util.List;

//
// 模拟退火算法解决TSP旅行商问题
//
public class SimulatedAnnealing {

	public static List<City> allCitys = new ArrayList<City>();

    //计算 接受的概率
    public static double acceptanceProbability(int energy, int newEnergy, double temperature) {
        // 如果新的解决方案较优,就接受
        if (newEnergy < energy) {
            return 1.0;
        }
        return Math.exp((energy - newEnergy) / temperature);
    }

	//返回近似的 最佳旅行路径
	private static Tour sa() {
		// 初始化温度
        double temp = 10000;

        // 冷却概率
        double coolingRate = 0.003;

        // 初始化的解决方案
        Tour currentSolution = new Tour();
        currentSolution.generateIndividual();

        System.out.println("Initial solution distance: " + currentSolution.getDistance());

        // 设置当前为最优的方案
        Tour best = new Tour(currentSolution.getTour());

        // 循环知道系统冷却
        while (temp > 1) {
            // 生成一个邻居
            Tour newSolution = new Tour(currentSolution.getTour());

            // 获取随机位置
            int tourPos1 = (int) (newSolution.tourSize() * Math.random());
            int tourPos2 = (int) (newSolution.tourSize() * Math.random());

            City citySwap1 = newSolution.getCity(tourPos1);
            City citySwap2 = newSolution.getCity(tourPos2);

            // 交换
            newSolution.setCity(tourPos2, citySwap1);
            newSolution.setCity(tourPos1, citySwap2);

            // 获得新的解决方案的花费
            int currentEnergy = currentSolution.getDistance();
            int neighbourEnergy = newSolution.getDistance();

            // 决定是否接受新的 方案
            if (acceptanceProbability(currentEnergy, neighbourEnergy, temp) > Math.random()) {
                currentSolution = new Tour(newSolution.getTour());
            }

            // 记录找到的最优方案
            if (currentSolution.getDistance() < best.getDistance()) {
                best = new Tour(currentSolution.getTour());
            }

            // 冷却
            temp *= 1-coolingRate;
        }
		return best;
	}

	private static void init() {
		City city = new City(60, 200);
	    allCitys.add(city);
	    City city2 = new City(180, 200);
	    allCitys.add(city2);
	    City city3 = new City(80, 180);
	    allCitys.add(city3);
	    City city4 = new City(140, 180);
	    allCitys.add(city4);
	    City city5 = new City(20, 160);
	    allCitys.add(city5);
	    City city6 = new City(100, 160);
	    allCitys.add(city6);
	    City city7 = new City(200, 160);
	    allCitys.add(city7);
	    City city8 = new City(140, 140);
	    allCitys.add(city8);
	    City city9 = new City(40, 120);
	    allCitys.add(city9);
	    City city10 = new City(100, 120);
	    allCitys.add(city10);
	    City city11 = new City(180, 100);
	    allCitys.add(city11);
	    City city12 = new City(60, 80);
	    allCitys.add(city12);
	    City city13 = new City(120, 80);
	    allCitys.add(city13);
	    City city14 = new City(180, 60);
	    allCitys.add(city14);
	    City city15 = new City(20, 40);
	    allCitys.add(city15);
	    City city16 = new City(100, 40);
	    allCitys.add(city16);
	    City city17 = new City(200, 40);
	    allCitys.add(city17);
	    City city18 = new City(20, 20);
	    allCitys.add(city18);
	    City city19 = new City(60, 20);
	    allCitys.add(city19);
	    City city20 = new City(160, 20);
	    allCitys.add(city20);
	}
	
    public static void main(String[] args) {
        // 创建所有的城市城市列表
        init();
        
        //求解TSP问题
        Tour best = sa();
        System.out.println("Final solution distance: " + best.getDistance());
        System.out.println("Tour: " + best);
    }
}

package sa;

public class City {
    int x;
    int y;

    // 生成一个随机的城市
    public City(){
        this.x = (int)(Math.random()*200);
        this.y = (int)(Math.random()*200);
    }

    public City(int x, int y){
        this.x = x;
        this.y = y;
    }

    public int getX(){
        return this.x;
    }

    public int getY(){
        return this.y;
    }

    // 计算两个城市之间的距离
    public double distanceTo(City city){
        int xDistance = Math.abs(getX() - city.getX());
        int yDistance = Math.abs(getY() - city.getY());
        double distance = Math.sqrt( (xDistance*xDistance) + (yDistance*yDistance) );

        return distance;
    }

    @Override
    public String toString(){
        return getX()+", "+getY();
    }
}

package sa;

import java.util.ArrayList;
import java.util.Collections;

public class Tour{

    // 保持城市的列表
    private ArrayList tour = new ArrayList<City>();
    // 缓存距离
    private int distance = 0;

    // 生成一个空的路径
    public Tour(){
        for (int i = 0; i < SimulatedAnnealing.allCitys.size(); i++) {
            tour.add(null);
        }
    }

    // 复制路径
    public Tour(ArrayList tour){
        this.tour = (ArrayList) tour.clone();
    }

    public ArrayList getTour(){
        return tour;
    }

    // Creates a random individual
    public void generateIndividual() {
        // Loop through all our destination cities and add them to our tour
        for (int cityIndex = 0; cityIndex < SimulatedAnnealing.allCitys.size(); cityIndex++) {
          setCity(cityIndex, SimulatedAnnealing.allCitys.get(cityIndex));
        }
        // 随机的打乱路径
        Collections.shuffle(tour);
    }

    // 获取一个城市
    public City getCity(int tourPosition) {
        return (City)tour.get(tourPosition);
    }

    public void setCity(int tourPosition, City city) {
        tour.set(tourPosition, city);
        // 重新计算距离
        distance = 0;
    }

    // 获得当前距离的 总花费
    public int getDistance(){
        if (distance == 0) {
            int tourDistance = 0;
            for (int cityIndex=0; cityIndex < tourSize(); cityIndex++) {
                City fromCity = getCity(cityIndex);
                City destinationCity;
                if(cityIndex+1 < tourSize()){
                    destinationCity = getCity(cityIndex+1);
                }
                else{
                    destinationCity = getCity(0);
                }
                tourDistance += fromCity.distanceTo(destinationCity);
            }
            distance = tourDistance;
        }
        return distance;
    }

    // 获得当前路径中城市的数量
    public int tourSize() {
        return tour.size();
    }

    @Override
    public String toString() {
        String geneString = "|";
        for (int i = 0; i < tourSize(); i++) {
            geneString += getCity(i)+"|";
        }
        return geneString;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值