可变数量的嵌套 for 循环
编辑:抱歉,但我忘了提及我需要计数器变量的值。因此,恐怕制作一个循环并不是一种解决方案。
我不确定这是否可能,但我想执行以下操作。 向函数传递一个数字数组。每个数字都是一个for循环的上限,例如,如果数组是[2, 3, 5]
,则应执行以下代码:
for(var a = 0; a < 2; a++) {
for(var b = 0; b < 3; b++) {
for(var c = 0; c < 5; c++) {
doSomething([a, b, c]);
}
}
}
因此嵌套的for循环数量等于数组的长度。有什么办法可以让这项工作发挥作用吗?我正在考虑创建一段代码,将每个 for 循环添加到一个字符串中,然后通过 eval
对其进行评估。然而,我读到 eval
不应该是一个人的首选,因为它也可能产生危险的结果。
什么技术可能适合这里?
Edit: I'm sorry, but I forgot to mention that I'll need the values of the counter variables. So making one loop isn't a solution I'm afraid.
I'm not sure if this is possible at all, but I would like to do the following.
To a function, an array of numbers is passed. Each number is the upper limit of a for loop, for example, if the array is [2, 3, 5]
, the following code should be executed:
for(var a = 0; a < 2; a++) {
for(var b = 0; b < 3; b++) {
for(var c = 0; c < 5; c++) {
doSomething([a, b, c]);
}
}
}
So the amount of nested for loops is equal to the length of the array. Would there be any way to make this work? I was thinking of creating a piece of code which adds each for loop to a string, and then evaluates it through eval
. I've read however that eval
should not be one's first choice as it can have dangerous results too.
What technique might be appropriate here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
递归可以巧妙地解决这个问题:
这样调用:
Recursion can solve this problem neatly:
Call it like this:
递归在这里是多余的。您可以使用生成器:
这里的直觉是我们保留一个始终小于相应长度的索引列表。
第二个循环处理进位。就像十进制数 199 递增一样,我们转到 (1, 9, 10),然后进位得到 (1, 10, 0),最后得到 (2, 0, 0)。如果我们没有足够的数字来进位,我们就完成了。
Recursion is overkill here. You can use generators:
The intuition here is that we keep a list of indices that are always less than the corresponding length.
The second loop handles carry. As when incrementing a decimal number 199, we go to (1, 9, 10), and then carry to get (1, 10, 0) and finally (2, 0, 0). If we don't have enough digits to carry into, we're done.
设置一个与限制数组长度相同的计数器数组。使用单个循环,并在每次迭代中递增最后一项。当它达到限制时,您可以重新启动它并增加下一个项目。
Set up an array of counters with the same length as the limit array. Use a single loop, and increment the last item in each iteration. When it reaches it's limit you restart it and increment the next item.
一种在编程上不会变得复杂的解决方案是获取整数并将它们全部相乘。由于您只嵌套 if,并且只有最里面的 if 具有功能,因此这应该可行:
或者:
One solution that works without getting complicated programatically would be to take the integers and multiply them all. Since you're only nesting the ifs, and only the innermost one has functionality, this should work:
Alternatively:
不要考虑嵌套的 for 循环,而是考虑递归函数调用。要进行迭代,您需要做出以下决定(伪代码):
这可能看起来像这样:
您将使用一个参数(即计数限制列表)和一个参数(即要为每个限制执行的函数)调用该函数。有效计数数组(“doSomething”部分)。上面的 main 函数在内部函数中完成了所有实际工作。在该内部函数中,第一个参数是计数器限制列表,当函数被递归调用时,它将被“削减”。第二个参数用于保存当前的计数器值集,以便“doSomething”可以知道它处于与实际计数的特定列表相对应的迭代中。
调用该函数将如下所示:
Instead of thinking in terms of nested
for
loops, think about recursive function invocations. To do your iteration, you'd make the following decision (pseudo code):That might look something like this:
You'd call the function with an argument that's your list of count limits, and an argument that's your function to execute for each effective count array (the "doSomething" part). The main function above does all the real work in an inner function. In that inner function, the first argument is the counter limit list, which will be "whittled down" as the function is called recursively. The second argument is used to hold the current set of counter values, so that "doSomething" can know that it's on an iteration corresponding to a particular list of actual counts.
Calling the function would look like this:
这是我尝试简化非递归Mike Samuel的解决方案。我还添加了为每个整数参数设置范围(不仅仅是最大值)的功能。
This is my attempt at simplifying the non-recursive solution by Mike Samuel. I also add the ability to set a range (not just maximum) for every integer argument.
进行 3 个 2、3、5 的循环和 1 个 30 (2*3*5) 的循环没有区别。
使用:
There's no difference between doing three loops of 2, 3, 5, and one loop of 30 (2*3*5).
Use:
您可以使用贪心算法来枚举笛卡尔积 0:2 x 0:3 x 0:5 的所有元素。该算法由下面的函数
greedy_backward
执行。我不是 Javascript 专家,也许这个功能可以改进。它按照反字典顺序枚举笛卡尔积的元素(您将在
doSomething
示例中看到完整的枚举):这是二进制表示的概括(
sizes 时的情况) =[2,2,2,...]
)。示例:
如果需要,反向操作很简单:
示例:
You can use the greedy algorithm to enumerate all elements of the cartesian product 0:2 x 0:3 x 0:5. This algorithm is performed by my function
greedy_backward
below. I am not an expert in Javascript and maybe this function could be improved.It enumerates the elements of the Cartesian product in the anti-lexicographic order (you will see the full enumeration in the
doSomething
example):This is a generalization of the binary representation (the case when
sizes=[2,2,2,...]
).Example:
If needed, the reverse operation is simple:
Example :
还可以使用生成器来实现:
然后可以将其用作:
One could also use a generator for that:
That can then be used as: