开发者

Recursion with loops (generating data)

开发者 https://www.devze.com 2023-02-16 09:01 出处:网络
Hello I need to know if it is possible to do something like this with recursion and how? I want to be able to choose how many loops I want, for instance GenerateNumbers(x) where x is numbers of loops

Hello I need to know if it is possible to do something like this with recursion and how? I want to be able to choose how many loops I want, for instance GenerateNumbers(x) where x is numbers of loops I have inside.

int a, b, c;
for (a = 0; a < 10; a++)
{
    printf("\n%d", 开发者_如何学编程a);
    for (b = 0; b < 10; b++)
    {
        printf("\n%d%d", a, b);
        for (c = 0; c < 10; c++)
        {
            printf("\n%d%d%d", a, b, c);
        }
    }
}


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



int GenerateNumbersHelper(int depth,int max_depth,int* data)
{
    int i;
    if(depth == 1 + max_depth)
        return 0;

    for(i=0;i<depth;i++)
    {
        printf("%i",data[i]);
    }
    printf("\n");
    for(i=0;i<10;i++)
    {
        data[depth]=i;
        GenerateNumbersHelper(depth+1,max_depth,data);
    }
    return 0;
}

int GenerateNumbers(int depth)
{
     int* data;
     data = malloc(sizeof(int)*depth);
     GenerateNumbersHelper(0,depth,data);
     free(data);
}

int main(void)
{
    GenerateNumbers(3);
}


Something like this?

void PrintCombinations(unsigned int CombinationLength)
{
    int * state = calloc(CombinationLength, sizeof(*state));
    Recurse(state, CombinationLength, CombinationLength);
    free(state);
}

void Recurse(int State[], size_t StateSize, unsigned int Depth)
{
    if(Depth)
    {
        for(State[Depth-1]=0; State[Depth-1]<10; State[Depth-1]++)
            Recurse(State, StateSize, Depth-1);
    }
    else
    {
        putchar('\n');
        for(;StateSize; StateSize--)
            printf("%d",State[StateSize-1]);
    }
}

(notice: this is C code, since you used printf in your example; if it were C++ the state array would have to be wrapped in a smart pointer like std::auto_ptr or std::unique_ptr in C++0x)

Notice that you can emulate this kind of recursion also with iteration, see for example this other answer of mine.


It is indeed possible. You need to use a stack structure or at the very least an array if there is an upper bound on x.

0

精彩评论

暂无评论...
验证码 换一张
取 消