I'm looking to implement the simulated annealing algorithm in Java to find an optimal route for the Travelling Salesman Problem, so far I have implemented brute force and am looking to modify that code in order to use simulated annealing. Obviously brute-force and simulated annealing are very different and use very different functions.
I understand simulated annealing uses a variable known as the temperature which then cools as the algorithm runs; with the temperature starting high and it gradually cooling throughout. Whilst the temperature is high the algorithm is more likely to choose solutions which are worse than the current, eliminating local maxima as you'd find in the similar hill-climbing algorithm. As it cools the algorithm is more unlikely to accept worse solutions and so it can focus on a specific area and an optimum route is found quickly.
I believe I understand how the algorithm works but am having trouble putting this into Java, I have 2 classes; one called City which just contains methods to work out details of each city such as getIndex
, getDistance
, etc.
The algorithm class reads from an input file and stores it in an array (int [][]
)
The code below is the algorithm for brute-force which is what I want to modify to do simulated annealing instead, if anyone could help me do that I'd appreciate it massively.
public static void doBF()
{
int random1 = generateRand();
if (towns2.size() > random1)
{
Town town = towns2.get(random1);
visitedTowns[i] = town;
towns2.remove(town);
i++;
if (lastTown != 1000)
{
journey += town.getDistance(lastTown);
}
lastTown = town.getIndex();
}
else
{
doBF();
}
}