N Loop

Generalize the for loop to be nested n-dimensionally. Provide capability to generalize and print any computational sequence nCk_nC_k.

EXAMPLE

n_for(3,3)

0 1 2
0 1 3
0 2 3
1 2 3

n_for(4,4)

0 1 2 3
0 1 2 4
0 1 3 4
0 2 3 4
1 2 3 4

Current progress: working with 1 and 3's. There is an issue on how index gets adjusted.

void manual_for_n1() {
    const int limit = 1;
    for (int i = 0; i <= limit; i++) {
        cout << i << endl;
    }
    cout << "__________________________\n\n";
}

void manual_for_n2() {
    const int limit = 2;
    for (int i = 0; i <= limit; i++) {
        for (int j = i + 1; j <= limit; j++) {
            cout << i << " " << j << endl;
        }
    }
    cout << "__________________________\n\n";
}

void manual_for_n3() {
    const int limit = 3;
    for (int i = 0; i <= limit; i++) {
        for (int j = i + 1; j <= limit; j++) {
            for (int k = j + 1; k <= limit; k++) {
                cout << i << " " << j << " " << k << endl;
            }
        }
    }
    cout << "__________________________\n\n";
}

void manual_for_n4() {
    const int limit = 4;
    for (int i = 0; i <= limit; i++) {
        for (int j = i + 1; j <= limit; j++) {
            for (int k = j + 1; k <= limit; k++) {
                for (int l = k + 1; l <= limit; l++) {
                    cout << i << " " << j << " " << k << " " << l << endl;
                }
            }
        }
    }
    cout << "__________________________\n\n";
}

/*
 *     ijk: maintains the current state of for loop variables (i,j,k...)
 * ijk_ref: points current state (i,j,k...) to the previous state + 1
 * go_till: fixed integer for for loop terminating condition
 *   index: what variable (i,j,k...) is being reference at a given moment in for loop
 * num_for: fixed size of number of for loops
 * counter: counts up to limit num_for to end number of for loops
 *
 */
void n_for_rec(vector<int> &ijk, vector<int*> &ijk_ref, const int &go_till, int index, const int num_for, int &counter)
{
    if (counter < num_for) {
        for (ijk[index] = *ijk_ref[index] + 1; ijk[index] < go_till; ++ijk[index], ++index) {
            n_for_rec(ijk, ijk_ref, go_till, index + 1, num_for, ++counter);

            for (int j : ijk) cout << j << " ";
            cout << endl;
        }
    }
}

void n_for(const int num_for, const int go_till) {
    int i = -1;
    vector<int> ijk(num_for);
    vector<int*> ijk_ref(num_for);

    ijk_ref[0] = &i;
    for (int i = 1; i < num_for; i++)
        ijk_ref[i] = &(ijk[i - 1]);

    int index = 0, counter = 0;
    n_for_rec(ijk, ijk_ref, go_till, index, num_for, counter);
    cout << "__________________________\n\n";
}


int main()
{
    //manual_for_n1();
    //n_for(1, 1);

    manual_for_n2();
    n_for(2, 2);

    manual_for_n3();
    n_for(3, 3);

    manual_for_n4();
    n_for(4, 4);
}

Last updated