C ++可变数量的嵌套循环

时间:2014-08-05 11:47:00

标签: c++ loops variables recursion nested

我想创建一个函数,根据嵌套循环的深度,这样做:

如果深度= 1:

for(i = 0; i < max; i++){
    pot[a++] = wyb[i];
}

如果深度= 2:

for(i = 0; i < max; i++){
    for( j = i+1; j < max; j++){
        pot[a++] = wyb[i] + wyb[j];
    }
}

如果深度= 3:

for(i = 0; i < max; i++){
    for( j = i+1; j < max; j++){
        for( k = j+1; k < max; k++){
            pot[a++] = wyb[i] + wyb[j] + wyb[k];
        }
    }
}

等等。

结果将是:

深度= 1

pot[0] = wyb[0]
pot[1] = wyb[1]
...
pot[max-1] = wyb[max-1]

深度= 2,最大= 4

pot[0] = wyb[0] + wyb[1]
pot[1] = wyb[0] + wyb[2]
pot[2] = wyb[0] + wyb[3]
pot[3] = wyb[1] + wyb[2]
pot[4] = wyb[1] + wyb[3]
pot[5] = wyb[2] + wyb[3]

我想你明白了。我无法想出一种巧妙地做到这一点的方法。

有人能提出一种简单的方法来使用递归(或者可能不是吗?)来实现这一点,记住我仍然是c ++的初学者,指出我正确的方向吗?

感谢您的时间。

2 个答案:

答案 0 :(得分:3)

您可以使用std::next_permutation来管理组合:

std::vector<int> compute(const std::vector<int>& v, std::size_t depth)
{
    if (depth == 0 || v.size() < depth) {
        throw "depth is out of range";
    }
    std::vector<int> res;
    std::vector<int> coeffs(depth, 1);
    coeffs.resize(v.size(), 0); // flags is now {1, .., 1, 0, .., 0}

    do {
        int sum = 0;
        for (std::size_t i = 0; i != v.size(); ++i) {
            sum += v[i] * coeffs[i];
        }
        res.push_back(sum);
    } while (std::next_permutation(coeffs.rbegin(), coeffs.rend()));
    return res;
}

Live example

答案 1 :(得分:0)

简化的递归版本:

int *sums_recursive(int *pot, int *wyb, int max, int depth) {
    if (depth == 1) {
        while (max--)
            *pot++ = *wyb++;
        return pot;
    }
    for (size_t i = 1; i <= max - depth + 1; ++i) {
        int *pot2 = sums_recursive(pot, wyb + i, max - i, depth - 1);
        for (int *p = pot ; p < pot2; ++p) *p += wyb[i - 1];
        pot = pot2;
    }
    return pot;
}

迭代版本:

void sums(int *pot, int *wyb, int max, int depth) {
    int maxi = 1;
    int o = 0;
    for (int d = 0; d < depth; ++d) { maxi *= max; }
    for (int i = 0; i < maxi; ++i) {
        int i_div = i;
        int idx = -1;
        pot[o] = 0;
        int d;
        for (d = 0; d < depth; ++d) {
            int new_idx = i_div % max;
            if (new_idx <= idx) break;
            pot[o] += wyb[new_idx];
            idx = new_idx;
            i_div /= max;
        }
        if (d == depth) o++;
    }
}
相关问题