我正在尝试制作一个螺旋生成器,该生成器通过答案应具有的维度数量进行参数化。
二维 (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 循环
,其中我将 t
作为输入,并保存一个包含 的数组,那就足够了>x
-在x, y
情况下的值;在 x, y, z
的情况下保存 x, y
值; x, y, z
值(如果是 x, y, z, alpha
等)
我希望我的问题足够清楚。
最佳答案
好吧,有一个适用于整数的解决方案,而不是停滞不前,通用解决方案要困难得多,注意:这将在盒子中“螺旋”出来。
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]
关于java - 将固定数量的 for 循环转换为参数化数量时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18074982/