我目前正在做一个项目 (TSP),并尝试将一些模拟退火伪代码转换为 Java 代码。 过去我曾成功地将伪代码转换为 Java 代码,但这次却无法成功转换。
伪代码如下:
T0(T and a lowercase 0) Starting temperatureIter Number of iterationsλ The cooling rate1. Set T = T0 (T and a lowercase 0)2. Let x = a random solution3. For i = 0 to Iter-14. Let f = fitness of x5. Make a small change to x to make x’6. Let f’ = fitness of new point7. If f’ is worse than f then8. Let p = PR(f’, f, Ti (T with a lowercase i))9. If p > UR(0,1) then10. Undo change (x and f)11. Else12. Let x = x’13. End if14. Let Ti(T with a lowercase i) + 1 = λTi(λ and T with a lowercase i)15. End forOutput: The solution x
如果有人能展示一下这个在 Java 中的基本实现,我将非常感激 – 我似乎就是搞不明白!
我正在使用多个类和许多函数(我不会列出,因为它与我所问的无关)。我已经有一个 smallChange()
方法和一个 fitness
函数 – 是否有可能需要创建多个不同版本的这些方法? 例如,我有类似这样的:
public static ArrayList<Integer> smallChange(ArrayList<Integer> solution){//Code is here.}
我是否可能需要此方法的另一个版本,该版本接受不同的参数? 类似如下:
public static double smallChange(double d){//Code is here.}
我所需要的只是对如何在 Java 中编写这个有一个基本的了解 – 一旦我知道它在正确的语法中应该是什么样子,我就能够将它应用到我的代码中,但是我似乎无法克服这个障碍。
回答:
基本代码应该像这样:
public class YourClass { public static Solution doYourStuff(double startingTemperature, int numberOfIterations, double coolingRate) { double t = startingTemperature; Solution x = createRandomSolution(); double ti = t; for (int i = 0; i < numberOfIterations; i ++) { double f = calculateFitness(x); Solution mutatedX = mutate(x); double newF = calculateFitness(mutatedX); if (newF < f) { double p = PR(); // no idea what you're talking about here if (p > UR(0, 1)) { // likewise // then do nothing } else { x = mutatedX; } ti = t * coolingRate; } } return x; } static class Solution { // no idea what's in here... }}
至于想要 smallChange() 方法的不同版本 – 完全可以做到,但你必须阅读一些关于继承的内容。