如果不知道 n 是什么,我该如何编写 n 个嵌套的 for 循环? 例如,我将如何使用递归或其他方法来编写此代码:
for (int i = 0; cond1; i++){
for (int j = 0; cond2; j++){
for (int k = 0; cond3; k++)
...
for (int l = 0; cond_N; l++){
if (.....) break;
}
}
}
}
这里,有 n 个带有某些条件的循环(每个变量的条件不一定相同),并且我不确定如何在不知道 n 是什么的情况下使用递归将其转换为代码。谢谢!
这就是你想要做的吗?
cond
提供了N个不同的条件(即循环变量相关的布尔函数)并且foo
引入了递归:
#include <iostream>
bool cond(int cond_which, int current_loop_variable) {
switch (cond_which) {
case 0:
return current_loop_variable < 5;
case 1:
return current_loop_variable < 3;
/* more... can be hella complicated, related with states, whatever */
default:
return false;
}
}
void foo(int we_may_call_it_the_meta_loop_variable) {
for (int i = 0; cond(we_may_call_it_the_meta_loop_variable, i); ++i) {
foo(we_may_call_it_the_meta_loop_variable + 1);
std::cout << "in loop " << we_may_call_it_the_meta_loop_variable << ", i = " << i << std::endl;
}
};
int main() {
foo(0);
return 0;
}
显然这不是无限递归。
这是这个问题的一个应用。例如,找到 3 个棒材长度的棒材切割组合。因此,切割 20 英尺长的钢筋后,废料的长度不应超过 1 英尺。所以,我使用了 3 个嵌套循环,因为有 3 个条形剪切。如果我有 50 个小节剪切,那么我将使用 50 个嵌套循环。那么,我们如何使用递归来重写它呢?谢谢。 c++中的相关问题
要求(从问题逆向工程):
- the body of the loop knows which iteration it is for self and all parents
- the number of loops is between 0 and at least hundreds
- memory allocation is no problem i.e. no attempt at limiting it via compartmentalization is required
- manual termination of current(but not parent) loop is available
- loop counters are int and count upwards from zero
- no code is executed except in the leaf loop
- recursion not compulsory
这里有一个试图让大家理解这个想法的尝试,我们将尝试根据兴趣进行编译:
using Counter = int;
using State = std::vector<Counter>;
using Condition = std::function<bool(const State &)>;
using Action = std::function<void(const State &)>;
void run(const std::vector<Condition> & conditions, Action action)
{
std::vector<Counter> state(conditions.size(), 0);
unsigned depth{};
while(depth < conditions.size() && ! conditions[conditions.size()-1-depth])
{
if(conditions[conditions.size()-1-depth](state))
{
action(state);
}
else
{
// Go up the stack of loops.
while(depth++ < state.size())
{
state[state.size()-1-depth] = 0
++state[state.size()-2-depth];
}
}
}
}