java使用退火算法处理旅行商问题demo
以下是一个简单的 Java 退火算法的示例,用于解决旅行商问题(TSP):
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class SimulatedAnnealingTSP {
static class City {
int x, y;
public City(int x, int y) {
this.x = x;
this.y = y;
}
public double distanceTo(City other) {
int dx = x - other.x;
int dy = y - other.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
// 计算路径的总距离
static double totalDistance(List<Integer> path, List<City> cities) {
double dist = 0;
for (int i = 0; i < path.size() - 1; i++) {
int cityIndex1 = path.get(i);
int cityIndex2 = path.get(i + 1);
City city1 = cities.get(cityIndex1);
City city2 = cities.get(cityIndex2);
dist += city1.distanceTo(city2);
}
return dist;
}
// 退火算法函数
static List<Integer> simulatedAnnealing(List<City> cities, double temperature, double coolingRate) {
List<Integer> currentPath = new ArrayList<>();
for (int i = 0; i < cities.size(); i++) {
currentPath.add(i);
}
List<Integer> bestPath = new ArrayList<>(currentPath);
double currentDistance = totalDistance(currentPath, cities);
double bestDistance = currentDistance;
Random random = new Random();
while (temperature > 1) {
int index1 = random.nextInt(cities.size());
int index2 = random.nextInt(cities.size());
swap(currentPath, index1, index2);
double newDistance = totalDistance(currentPath, cities);
double delta = newDistance - currentDistance;
if (delta < 0 || Math.exp(-delta / temperature) > random.nextDouble()) {
currentDistance = newDistance;
if (currentDistance < bestDistance) {
bestDistance = currentDistance;
bestPath = new ArrayList<>(currentPath);
}
} else {
// 恢复交换之前的路径
swap(currentPath, index1, index2);
}
temperature *= coolingRate;
}
return bestPath;
}
// 交换列表中的两个元素
static void swap(List<Integer> list, int i, int j) {
int temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);
}
public static void main(String[] args) {
List<City> cities = Arrays.asList(
new City(0, 0),
new City(1, 2),
new City(3, 1),
new City(5, 2),
new City(6, 4)
);
double initialTemperature = 10000;
double coolingRate = 0.999;
List<Integer> bestPath = simulatedAnnealing(cities, initialTemperature, coolingRate);
System.out.println("最优路径: " + bestPath);
System.out.println("最优距离: " + totalDistance(bestPath, cities));
}
}
在这个示例中,我们定义了 City 类来表示城市,并实现了 totalDistance 方法来计算路径的总距离。然后,我们实现了 simulatedAnnealing 方法来执行退火算法。在主函数中,我们给出了一个简单的城市列表,并调用 simulatedAnnealing 方法来找到最优路径。