How to make n nested for a loop in C or Objective C

How to do something like this

for(int a = 0; a<2; a++){
        for(int b = 0; b<2; b++){
            for(int c = 0; c<2; c++){
                for(int d = 0; d<2; d++){

                    n[a+b+c+d]=x[a]*y[b]*z[c]...
}}}}

But I have x [n] ...

+3
source share
3 answers

Recursive:

void do_sum(double *n, double *x, int limit, int index, double sum)
{
    if (limit == 0)
        n[index] = sum;
    else
        for (int a = 0; a<2; a++)
            do_sum(n, x, limit-1, index+a, sum+x[a]);
}

To start recursion, start with do_sum(n, x, max_n, 0, 0)

+3
source

@jbx is right: recursively is the way to go. Assuming that n[]and x[]are global:

void
work(int depth, int n_index, int x_total)
{
    if (depth == 0) {
        n[n_index] = x_total;
    }
    else {
        for (int i = 0; i < 2; i++) {
            work(depth-1, n_index+i, x_total+x[i]);
        }
    }
}

void
do_multidimensional_thing(int depth)
{
    work(depth, 0, 0);
}
0
source

2 , .. 2 * N . - , n [] , :

a = 0, b = 1, c = 0, d = 1 a = 1, b = 1, c = 0, d = 0 ...

n [a + b + c + d] n [2] C (4,2) .. , .

.

But if anything - I would go with the backtracking (recursion) method if this is really what the user wants. (especially if there are N dimensions - since there is no real great way to do this thing iteratively if you don't want to use dp on this, which is probably above the end-user’s head)

0
source

Source: https://habr.com/ru/post/1783026/


All Articles