受控嵌套循环

时间:2011-08-25 01:35:58

标签: c algorithm recursion permutation

我有嵌套循环(r =)3次。每个循环运行(n =)5次。

for (i=0; i<n; i++)
{
    for (j=0; j<n; j++)
    {
        for (k=0; k<n; k++)
        //
    }
}

但是我们如何在运行时动态嵌套。假设我们知道它应该嵌套r次。每个循环运行n次。我觉得像递归一样,但它无限期地发生。

funloop (int r)
{
     for (int i = 0; i < n; i++)
     {
          //
          if (r < 3)
              funloop (r++);
          else
              return;
      }
}

请让我知道如何做到这一点?我无法在网上找到消息来源。

5 个答案:

答案 0 :(得分:3)

如果静态地不知道递归的深度,最常用的方法是使用递归来表示循环。例如,假设您需要具有d级嵌套循环,这些循环都需要迭代k次。然后你可以使用这种形式的递归来实现它:

void RecursivelyNestIterations(unsigned d, unsigned k) {
    /* Base case: If the depth is zero, we don't need to iterate. */
    if (d == 0) return;

    /* Recursive step: If we need to loop d times, loop once, calling the
     * function recursively to have it loop d - 1 times.
     */
    for (unsigned i = 0; i < k; ++i) {
         /* Recurse by looping d - 1 times using the same number of iterations. */
         RecursivelyNestIterations(d - 1, k);
    }
}

希望这有帮助!

答案 1 :(得分:1)

最简单的方法就是将其折叠为一个for循环:

for(i=0; i<pow(n, r); i++) {
}

但是,如果需要,可能会很难访问循环计数器,但这可以通过数学方式完成。例如,最里面的循环计数器变量值由下式给出:

int c = i % n;

你可以有一个这样的计数器数组并用类似的方程确定值,或者你可以在需要时增加它们,例如:

void iterate(int r, int n) {
  int i, rc, *c = malloc(sizeof(int) * r);

  memset(c, 0, sizeof(int) * r);
  for(i = 0; i < pow(n, r); i++) {

    // code here, using loop counters in the 'c' array, where c[0] is counter
    // for the outer loop, and c[r - 1] is the counter for the innermost loop

    // update the counters
    rc = r;
    while(rc > 0) {
      rc--;
      c[rc]++;
      if(c[rc] == n) {
        c[rc] = 0;
      } else {
        break;
      }
    }
  }
  free(c); 
}

答案 2 :(得分:0)

只需在循环体中调用if (r) funloop(r-1);

答案 3 :(得分:0)

#include <stdlib.h>
#include <stdio.h>

static int n = 3;

void _funloop(int cur,int total)
{
    if(cur!=total)
    {
        for(int cnt=0;cnt!=n;++cnt)
        {
            fprintf(stdout,"%d::%d\n",cur,cnt);
        }

        _funloop(cur+1,total);
    }
}

void funloop(int total)
{
    _funloop(0,total);
}

int main()
{
    funloop(10);

    return 0;
}

答案 4 :(得分:0)

本提示讨论了一种不使用递归的解决方案 [链接] http://www.codeproject.com/Tips/759707/Generating-dynamically-nested-loops 代码用C ++编写,需要#用于include和define语句

include <iostream>
define MAXROWS 9
define MAXVALUES 9

using namespace std;
char display[] = {'1','2','3','4','5','6','7','8','9'};

int main() {

int arrs[MAXROWS];  // represent the different variables in the for loops

bool status = false;

for (int r=0;r<MAXROWS;r++)
    arrs[r] = 0;  // Initialize values

while (!status) { 

    int total = 0;
    // calculate total for exit condition
    for (int r=0;r<MAXROWS;r++)
        total +=arrs[r];
    // test for exit condition
    if (total == (MAXVALUES-1)*MAXROWS)
        status = true;

    // printing
    for (int r=0;r<MAXROWS;r++)
        cout << display[arrs[r]]; // print(arrs[r])
    cout << endl;  // print(endline)

    // increment loop variables
        bool change = true;
    int r = MAXROWS-1;  // start from innermost loop
    while (change && r>=0) {
        // increment the innermost variable and check if spill overs
        if (++arrs[r] > MAXVALUES-1) {        
            arrs[r] = 0;  // reintialize loop variable
            // Change the upper variable by one
            // We need to increment the immediate upper level loop by one
            change = true;
        }
        else
            change = false; // Stop as there the upper levels of the loop are unaffected

        // We can perform any inner loop calculation here arrs[r]

        r=r-1;  // move to upper level of the loop

    }

}