variable nested for loops

前端 未结 6 1665
南旧
南旧 2020-12-01 20:15

I\'m trying to figure out how I can use recursion to do n-level nested for loops. For example, if n=3, there would be 3 \'levels\'

for(z=0;z<6;z++){
   fo         


        
6条回答
  •  误落风尘
    2020-12-01 20:44

    You are very vague about why you want this. For a starter a possible solution is to replace each for loop with a recursive function.

    void recursiveX(int zVal, int yVal, int xVal)
    {
        if(zVal+yVal+xVal == f)...
        if(xVal != 0)
            recursiveX(zVal, yVal, xVal -1);
    }
    
    void recursiveY(int zVal, int yVal)
    {
        recursiveX(zVal, yVal, 6);
        if(yVal != 0)
            recursiveY(zVal, yVal-1);
    }
    
    void recursiveZ(int val)
    {
        recursiveY(val, 6);
        if(val != 0)
            recursiveZ(val-1);
    }
    ...
    recursiveZ(6);
    

    And in the end you can merge this all into one function. Nevertheless using recursion just because it is possible is never a good Idea.

提交回复
热议问题