0

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

Jarod42
  • 203,559
  • 14
  • 181
  • 302
shirin
  • 175
  • 2
  • 14
  • 1
    It is not permutations that you want but combinations (even if the solution I gave is with permutation of *mask*). – Jarod42 Dec 21 '15 at 11:31
  • Yes, because order of members is important, so it is combination not permutation.tnx – shirin Dec 21 '15 at 11:59
  • @shirin that doesn't directly follow from your statement. For combinations, order generally doesn't matter. What you want is an *ordered combination* (which is a subset of the permutations of a set) – Joel Cornett Dec 21 '15 at 12:11
  • 1
    @JoelCornett I think you might have misunderstood the question. OP gave `{b,d,a}` as an example of what *not* to output, because they want the normalized form `{a,b,d}`. My interpretation is that they want exactly the m-combinations of the set A – Niklas B. Dec 21 '15 at 12:18
  • What have you done? Is there any code snippet to view? Are you asking us to solve your homework? Please, put this question on hold!! – Luis Colorado Dec 22 '15 at 09:55

1 Answers1

3

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

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • @NiklasB.: would be possible for a superset. In your suggestion, we have to count how many bit are set :/. (I may also add that if OP wants each pair of a vector of 129 element, your `int` is too short). – Jarod42 Dec 21 '15 at 12:33
  • You're right, is missed that part :) – Niklas B. Dec 21 '15 at 13:04