将固定数量的for循环转换为参数化量的麻烦

时间:2013-08-06 08:16:23

标签: java loops methods refactoring

我正在努力使Spirals的生成器按照答案应该具有的维度进行参数化。

2个维度的示例(x,y)

static void caller()
{
  for (int t = 0; t < 10; t++)
  for (int x = 0; x <= t; x++)
  {
     int y = (t-x);
     printAllPossibleSigns(0, x, y);
  }
}

3个维度(x,y,z)上的示例

static void caller()
{
  for (int t = 0; t < 10; t++)
  for (int x = 0; x <= t; x++)
  for (int y = 0; y <= (t-x); y++)
  {
     int z = (t-x-y);
     printAllPossibleSigns(0, x, y, z);
  }
}

4个维度(x,y,z,alpha)的示例

static void caller()
{
  for (int t = 0; t < 10; t++)
  for (int x = 0; x <= t; x++)
  for (int y = 0; y <= (t-x); y++)
  for (int z = 0; z <= (t-x-y); z++)
  {
     int alpha = (t-x-y-z);
     printAllPossibleSigns(0, x, y, z, alpha);
  }
}

但是现在我试图一次只生成1个结果(或一批结果):

那么如果我想将它用于迭代器,我现在需要怎么做呢,所以使用next()它应该检索一个printAllPossibleSigns(0, ...);调用的'结果'。

如果有一些方法替换我在for-loops中输入的t和一个包含x的数组的方法,那就足够了。 x, y;在x, y的情况下持有x, y, z - 值; x, y, z - x, y, z, alpha等情况下的值

我希望我的问题很清楚。

1 个答案:

答案 0 :(得分:2)

好吧,不是拖延,而是有一个解决方案适用于整数,一般的解决方案要困难得多,请注意:这将是&#34;螺旋&#34;在盒子里。

public static void main(String... ignored) {
    caller(10, 7, new Callback<int[]>() {
        @Override
        public void on(int[] ints) {
            System.out.println(Arrays.toString(ints));
        }
    });
}

interface Callback<T> {
    public void on(T t);
}

public static void caller(int maxSum, int dimensions, Callback<int[]> callback) {
    int[] ints = new int[dimensions];
    for (int t = 0; t < maxSum; t++) {
        caller(t, 0, ints, callback);
    }
}

private static void caller(int sum, int idx, int[] ints, Callback<int[]> callback) {
    if (idx == ints.length) {
        callback.on(ints);
        return;
    }
    for (int i = 0; i < sum; i++) {
        ints[idx] = i;
        caller(sum - i, idx+1, ints, callback);
    }
}

打印

[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 1]
[0, 0, 0, 0, 0, 1, 0]
[0, 0, 0, 0, 1, 0, 0]
[0, 0, 0, 1, 0, 0, 0]
[0, 0, 1, 0, 0, 0, 0]
[0, 1, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 2]
[0, 0, 0, 0, 0, 1, 1]
[0, 0, 0, 0, 0, 2, 0]
[0, 0, 0, 0, 1, 0, 1]
[0, 0, 0, 0, 1, 1, 0]
[0, 0, 0, 0, 2, 0, 0]
[0, 0, 0, 1, 0, 0, 1]
[0, 0, 0, 1, 0, 1, 0]
[0, 0, 0, 1, 1, 0, 0]
[0, 0, 0, 2, 0, 0, 0]

...

[7, 0, 1, 0, 0, 0, 1]
[7, 0, 1, 0, 0, 1, 0]
[7, 0, 1, 0, 1, 0, 0]
[7, 0, 1, 1, 0, 0, 0]
[7, 0, 2, 0, 0, 0, 0]
[7, 1, 0, 0, 0, 0, 1]
[7, 1, 0, 0, 0, 1, 0]
[7, 1, 0, 0, 1, 0, 0]
[7, 1, 0, 1, 0, 0, 0]
[7, 1, 1, 0, 0, 0, 0]
[7, 2, 0, 0, 0, 0, 0]
[8, 0, 0, 0, 0, 0, 1]
[8, 0, 0, 0, 0, 1, 0]
[8, 0, 0, 0, 1, 0, 0]
[8, 0, 0, 1, 0, 0, 0]
[8, 0, 1, 0, 0, 0, 0]
[8, 1, 0, 0, 0, 0, 0]
[9, 0, 0, 0, 0, 0, 0]