I don't want to show too much code, since it's part of an application belonging to my ongoing bachelor thesis. But here you go. The algorihtm should be kept very general. Take a look.
MAIN PART OF ALGORITHM
// one could check for minimum q factor to be satisfied here
while (temperature > 1)
{
state.step();
int next = state.energy();
if (acceptEnergyLevel(next))
{
energy = next;
if (energy < minEnergy)
{
minState = state.copy();
minEnergy = energy;
}
}
else
state.undo();
temperature *= DECAY_RATE;
}
STATE INTERFACE
public interface State<T extends State<T>>
{
public void step();
public void undo();
public int energy();
public T copy();
}
With this as basis for your algorithm you can solve any problem. Not just TSP. You just have to implement the State
interface, e.g. TspProblemInstance implements State<TspProblemInstance>
. The algorithm is generic and will return the optimum (or a result very near to the optimum) object of class TspProblemInstance
. Therefore it is important that you implement the copy
method diligently. The generic parameter T
is bound by the implementing class, i. e. the copy will always have type T
(a subtype could also be possible).
You should add some methods to your concrete implementation of the interface, that show you the sequence of the cities etc. The methods in the State
interface are only the minimum for the algorithm to work on.
I recommend the wiki article for further reading. And here two other implementations, the first is a bit complex, and the second is rather simple, but hackish (and not kept general). But they should give you more understanding of simulated annealing.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…