这是我对螺旋式方法的看法:
// this is your function
static void func(int x, int y)
{
System.out.println("x = "+x+", y = "+y);
}
// this calls func for all possible combinations of signs of the variables in arr
static void allPossibleSigns(int pos, Integer... arr)
{
if (pos == arr.length)
{
func(arr[0], arr[1]); // not really generic
}
else
{
allPossibleSigns(pos+1, arr);
arr[pos] = -arr[pos];
if (arr[pos] != 0)
allPossibleSigns(pos+1, arr);
}
}
static void caller()
{
for (int t = 0; t < MAX; t++)
for (int x = 0; x <= t; x++)
{
int y = (t-x);
allPossibleSigns(0, x, y);
}
}
如果您想要比 更通用的东西func(arr[0], arr[1]);
,可以将其替换为:
Method[] methods = NewMain.class.getMethods();
for (Method m: methods)
{
if (m.getName().equals("func"))
m.invoke(null, arr);
}
并添加一些错误检查。由于这种方法,我使用Integer...
而不是int...
in printAllPossibleSigns
(以上不适用于int...
)。这假设您只有一个名为func
. 如果不是这种情况,您将不得不添加一些额外的检查。
对于MAX
= 4,它打印:
x = 0, y = 0
x = 0, y = 1
x = 0, y = -1
x = 1, y = 0
x = -1, y = 0
x = 0, y = 2
x = 0, y = -2
x = 1, y = 1
x = 1, y = -1
x = -1, y = -1
x = -1, y = 1
x = 2, y = 0
x = -2, y = 0
x = 0, y = 3
x = 0, y = -3
x = 1, y = 2
x = 1, y = -2
x = -1, y = -2
x = -1, y = 2
x = 2, y = 1
x = 2, y = -1
x = -2, y = -1
x = -2, y = 1
x = 3, y = 0
x = -3, y = 0
这将如何扩展到 3 个变量可能并不完全清楚,所以这里是caller
3 个变量:
static void caller()
{
for (int t = 0; t < MAX; 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);
}
}
显然,func(arr[0], arr[1]);
如果您没有选择通用方法,那么这就是您必须更改的所有内容以及您的功能。