来自伪代码的 Java 模拟退火

标签 java algorithm artificial-intelligence pseudocode simulated-annealing

我目前正在从事一个项目 (TSP),并试图将一些模拟退火伪代码转换为 Java。我过去曾成功地将伪代码转换为 Java 代码,但我无法成功转换它。

伪代码是:

T0(T and a lowercase 0)    Starting temperature
Iter    Number of iterations
λ    The cooling rate

1.  Set T = T0 (T and a lowercase 0)
2.  Let x = a random solution
3.  For i = 0 to Iter-1
4.  Let f = fitness of x
5.  Make a small change to x to make x’
6.  Let f’ = fitness of new point
7.  If f’ is worse than f then
8.      Let p = PR(f’, f, Ti (T with a lowercase i))
9.      If p > UR(0,1) then
10.         Undo change (x and f)
11.     Else
12.         Let x = x’
13.     End if
14.     Let Ti(T with a lowercase i) + 1 = λTi(λ and T with a lowercase i)
15. End for
Output:  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() 方法而言 - 完全可行,但您必须稍微阅读一下继承

关于来自伪代码的 Java 模拟退火,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5439350/

相关文章:

java - 用Java处理和显示大量数据

java - 重现线程干扰

algorithm - 查找乘积大于总和的对

artificial-intelligence - 关于聚类方法的问题

swift - 如何在 Swift 中同时运行定时器和 AI 逻辑

java - 在 jUnit 中设置 JNDI 数据源

java - 从 OpenID 2.0 迁移到 OpenID Connect : cannot use the openid_id to select appengine users

algorithm - 将二进制数转换为 4 个 BCD 数字 - 除法是如何工作的?

algorithm - 是否存在完全不依赖顺序的编辑距离度量?

python - 对 Tensorflow 中的输入应用归一化