Stan
Stan

Reputation: 26501

Recursion with loops (generating data)

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);
        }
    }
}

Upvotes: 0

Views: 276

Answers (3)

Luka Rahne
Luka Rahne

Reputation: 10447

#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);
}

Upvotes: 1

Matteo Italia
Matteo Italia

Reputation: 126787

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.

Upvotes: 1

E.Beno&#238;t
E.Beno&#238;t

Reputation: 806

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.

Upvotes: 0

Related Questions