java - 遍历n维空间

标签 java algorithm search recursion multidimensional-array

我正在尝试编写一种算法,让我可以遍历 n 维空间内的所有所需点,以找到函数 f(x) 的最小值,其中 x 是大小为 n 的 vector 。

显然,搜索 2 维或 3 维空间非常简单,您可以简单地执行以下操作:

for(int i = 0; i < x; i++) {
    for(int j = 0; j < y; j++) {
        //and so on for however many dimensions you want

不幸的是,对于我的问题,空间的维数不是固定的(我正在为统计程序中的许多函数编写一个通用的最小值查找器)所以我必须为我想要的每个 n 值编写循环使用 - 最终可能会相当大。

我一直在努力思考如何使用递归来做到这一点,但看不到解决方案 - 尽管我确信那里有解决方案。

解决方案不一定是递归的,但它必须通用且高效(嵌套循环中最内层的行将被调用很多...)。

我表示搜索量的方式是一个二维 double 组:

double[][] space = new double[2][4];

这将表示一个 4d 空间,每个维度的最小和最大边界分别位于数组的位置 0 或 1。例如:

dim         0   1   2   3
    min(0):-10  5  10  -0.5
    max(1): 10 55  99   0.2

有什么想法吗?

最佳答案

总体思路如下:

interface Callback {
   void visit(int[] p); // n-dimensional point
}

// bounds[] - each number the limits iteration on i'th axis from 0 to bounds[i]
// current - current dimension
// callback - point
void visit(int[] bounds, int currentDimension, int[] p, Callback c) {
   for (int i = 0; i < bounds[currentDimension]; i++) {
        p[currentDimension] = i;
        if (currentDimension == p.length - 1) c.visit(p);
        else visit(bounds, currentDimension + 1, p, c);
   }
}

/// now visiting
visit(new int[] {10, 10, 10}, 0, new int[3], new Callback() {
   public void visit(int[] p) {
        System.out.println(Arrays.toString(p));
   }
});

关于java - 遍历n维空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10036904/

相关文章:

java.lang.UnsatisfiedLinkError 使用 native 接口(interface)

java - 在 Java 中打印一段单词中的每个单词,同时使用 Scanner 类跳过一些单词

search - 一致和可接受的启发式

php - 如何使输入字段将文本带入单独页面上的 Google 自定义搜索

Java程序没有从终端获得输出

java - 以编程方式调用 Google App 脚本和用户身份?

mysql 用户密码算法

python - 投注算法,特别是赢得赌注的算法?

c++ - boost中rtree中的打包算法

java - RegEx:如何在 Eclipse 中查找新类的实例?