gpt4 book ai didi

Java 递归超过 2 个参数和两个方向

转载 作者:行者123 更新时间:2023-12-01 23:40:21 25 4
gpt4 key购买 nike

我希望以通用方式同时递归两个参数。这里有一些解释:

函数调用应如下所示:Func(int a, int b):

  • 调用 0:Func(0, 0)
  • 调用 1:Func(0, 1)
  • 调用 1:Func(1, 0)
  • 调用 1:Func(0, -1)
  • 调用 1:Func(-1​​, 0)

我如何在代码中实现这一点,确保以下语句:

  • 考虑 a INRANGE (-INF, INF)b INRANGE (-INF, INF) 的所有可能组合。
  • 没有开销,我的意思是在递归中不会多次使用相同的函数。

我后来想将其扩展为通过 7 个参数执行相同的操作。

问候。

最佳答案

这是我对螺旋方法的看法:

// 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);
}

并添加一些错误检查。由于这种方法,我在 printAllPossibleSigns 中使用了 Integer... 而不是 int... (以上不适用于 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 个变量可能并不完全清楚,因此这里是 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]); 如果您没有选择通用方法。

关于Java 递归超过 2 个参数和两个方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18059220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com