开发者

How to make n nested for 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]...


Recursively:

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 initiate the recursion, start with do_sum(n, x, max_n, 0, 0)


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

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


Actually the depth for these is just 2 for each dimension., i.e., 2 * N total posibilities. Something that is weird that is it will access the same element in n[] for different values, overwriting things:

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

n[a + b + c + d] is actually just indexing into n[2] for C(4,2) etc. I think the actual question should be flagged and re-thought.

This doesn't seem like a well-thought question.

But if anything - I would go with the backtracking (recursion) method, if that's really what the user wants. (especially if there's N dimensions - as there's no real great way of doing this thing iteratively, unless you want to apply dp on this, which is probably over the head of the end user)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜