Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion of for's

Tags:

c++

recurrence

I'm tried to figure out how to do it for quite of time and its not working as intended; I'm writing a code where there is 1 to k numbers, I need to find all possible combination without repeats. e.g. for 3: 1, 2, 3, 12, 13.

Example for counting 4-digits numbers with 1, 2, 3, 4, 5.

int k = 5;
for (int p = 0; p < k; p++)
{
    for (int i = p+1; i < k; i++)
    {
        for (int j = i + 1; j < k; j++)
        {
            for (int h = j + 1; h < k; h++)
            {
                cout << p + 1 << i + 1 << j + 1 << h + 1 << endl;
            }
        }
    }
}

And there is example for 3-digits number with 1, 2, 3.

int k = 4
for (int p = 0; p < k; p++)
{
    for (int i = p+1; i < k; i++)
    {
        for (int j = i + 1; j < k; j++)
        {
            cout << p + 1 << i + 1 << j + 1 << endl;
        }
    }
}

I think that to count n-digits possible position without repeat i need n for's. And i don't know how to do it without recursion which don't work when i do it. My goal to get recursion which will count and print possible positions for n-digits.

like image 499
Sinma Avatar asked Oct 18 '22 23:10

Sinma


1 Answers

I did recursion to count possibility myself, but love you guys for all your help.

My recursion is

void col(int ilosc)
{
    static int st;
    for (int i = st++; i < k; i++)
    {
        if (ilosc > 1)
            col(ilosc - 1);
        else
            sposob++;
    }
}

where ilosc is digits number and sposob is count of possible positions numbers.

NOTE: sposob and k is global variables.

like image 113
Sinma Avatar answered Nov 03 '22 19:11

Sinma