producing m-member combination in a n-member array [duplicate]

这一生的挚爱 提交于 2019-12-12 03:53:50

问题


I have an array with n members. And I have another number: m,(m <= n) which is entered by user. Now I want to produce all of possible "m" member combination in the array.

A[5] = {a,b,c,d,e};
B = 3
Number of combination: C(5, 3) = 10

Now I want a code for showing these 10 combination.like:

{{a,b,c},{a,b,d},{a,b,e},.....}

Order of items in permutation is important. For example {a,b,d} is right but {b,d,a} is wrong. The permutation items should come in their order in our matrix.

I appropriate any help from your side. Thanks in advance


回答1:


For combination:

template <typename T>
void Combination(const std::vector<T>& v, std::size_t count)
{
    assert(count <= v.size());
    std::vector<bool> bitset(v.size() - count, 0);
    bitset.resize(v.size(), 1);

    do {
        for (std::size_t i = 0; i != v.size(); ++i) {
            if (bitset[i]) {
                std::cout << v[i] << " ";
            }
        }
        std::cout << std::endl;
    } while (std::next_permutation(bitset.begin(), bitset.end()));
}

Live demo



来源:https://stackoverflow.com/questions/34394366/producing-m-member-combination-in-a-n-member-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!