用遗传算法解决TSP问题java
时间: 2023-12-16 08:04:23 浏览: 84
使用遗传算法解决TSP问题(Java)
4星 · 用户满意度95%
好的,我能够帮你解答这个问题。
TSP问题是指在给定的一组城市中,找到一条最短的路径,使得每个城市恰好被访问一次,并最终回到起始城市。遗传算法是一种启发式优化算法,可以用于解决TSP问题。
下面是用遗传算法解决TSP问题的Java代码示例:
```java
import java.util.*;
public class TSPGeneticAlgorithm {
private int[][] distanceMatrix;
private int populationSize;
private int[][] population;
private int[] fitnessValues;
private int elitismCount;
private double mutationRate;
public TSPGeneticAlgorithm(int[][] distanceMatrix, int populationSize, int elitismCount, double mutationRate) {
this.distanceMatrix = distanceMatrix;
this.populationSize = populationSize;
this.elitismCount = elitismCount;
this.mutationRate = mutationRate;
population = new int[populationSize][distanceMatrix.length];
fitnessValues = new int[populationSize];
for (int i = 0; i < populationSize; i++) {
population[i] = generateRandomIndividual(distanceMatrix.length);
}
}
public int[] solve() {
int[] bestIndividual = null;
int bestFitness = Integer.MAX_VALUE;
int generationCount = 0;
while (generationCount < 1000) {
evaluatePopulation();
int[] elite = selectElite();
int[][] newPopulation = new int[populationSize][distanceMatrix.length];
newPopulation[0] = elite;
for (int i = 1; i < populationSize; i++) {
int[] parent1 = selectParent();
int[] parent2 = selectParent();
int[] offspring = crossover(parent1, parent2);
mutate(offspring);
newPopulation[i] = offspring;
}
population = newPopulation;
generationCount++;
if (fitnessValues[0] < bestFitness) {
bestIndividual = population[0];
bestFitness = fitnessValues[0];
}
}
return bestIndividual;
}
private void evaluatePopulation() {
for (int i = 0; i < populationSize; i++) {
int[] individual = population[i];
int fitness = calculateFitness(individual);
fitnessValues[i] = fitness;
}
Arrays.sort(population, (a, b) -> Double.compare(calculateFitness(a), calculateFitness(b)));
}
private int[] selectElite() {
int[][] elitePopulation = Arrays.copyOfRange(population, 0, elitismCount);
return Arrays.stream(elitePopulation).min((a, b) -> Integer.compare(calculateFitness(a), calculateFitness(b))).get();
}
private int[] selectParent() {
int index = 0;
double rouletteWheelPosition = Math.random();
while (rouletteWheelPosition > 0) {
rouletteWheelPosition -= calculateFitness(population[index]) / (double) getTotalFitness();
index++;
}
index--;
return population[index];
}
private int[] crossover(int[] parent1, int[] parent2) {
int[] offspring = new int[parent1.length];
int startPos = (int) (Math.random() * parent1.length);
int endPos = (int) (Math.random() * parent1.length);
for (int i = 0; i < offspring.length; i++) {
if (startPos < endPos && i > startPos && i < endPos) {
offspring[i] = parent1[i];
} else if (startPos > endPos) {
if (!(i < startPos && i > endPos)) {
offspring[i] = parent1[i];
}
}
}
for (int i = 0; i < parent2.length; i++) {
if (!contains(offspring, parent2[i])) {
for (int j = 0; j < offspring.length; j++) {
if (offspring[j] == 0) {
offspring[j] = parent2[i];
break;
}
}
}
}
return offspring;
}
private void mutate(int[] offspring) {
for (int i = 0; i < offspring.length; i++) {
if (Math.random() < mutationRate) {
int j = (int) (Math.random() * offspring.length);
int temp = offspring[i];
offspring[i] = offspring[j];
offspring[j] = temp;
}
}
}
private int calculateFitness(int[] individual) {
int fitness = 0;
for (int i = 0; i < individual.length - 1; i++) {
fitness += distanceMatrix[individual[i]][individual[i + 1]];
}
fitness += distanceMatrix[individual[individual.length - 1]][individual[0]];
return fitness;
}
private int[] generateRandomIndividual(int length) {
List<Integer> individual = new ArrayList<>();
for (int i = 0; i < length; i++) {
individual.add(i);
}
Collections.shuffle(individual);
return individual.stream().mapToInt(i -> i).toArray();
}
private boolean contains(int[] array, int value) {
for (int i : array) {
if (i == value) {
return true;
}
}
return false;
}
private int getTotalFitness() {
int totalFitness = 0;
for (int fitness : fitnessValues) {
totalFitness += fitness;
}
return totalFitness;
}
}
```
在上面的代码中,我们使用了遗传算法来解决TSP问题。其中,`distanceMatrix`表示城市之间的距离矩阵,`populationSize`表示种群大小,`elitismCount`表示精英数量,`mutationRate`表示变异率。
首先,我们随机生成一个初始种群。然后,我们对种群中的每个个体进行评估,计算其适应度值。接下来,我们按照适应度值对种群进行排序,并选择精英个体。然后,我们通过选择父母进行交叉和变异来生成新的后代个体。最后,我们将新的后代个体替换原来的种群,并继续迭代,直到达到最大迭代次数或找到最优解为止。
希望这个代码示例可以帮助到你。
阅读全文