duaa
duaa

Reputation: 31

getting all combinations from numbers without repeating

hi I work with c++ ,can I find easy way for getting an array from a set of numbers containing all possible combinations between ex : {1,2,3}

  { {3,1,2},
   {1,2,3},
   {3,2,1},
   {1,3,2},
   {2,1,3},
   {2,3,1}
  };

the problem if i get 5 or more numbers how to make there's 120 combination

Upvotes: 3

Views: 1777

Answers (1)

James McNellis
James McNellis

Reputation: 355307

Those are permutations, not combinations.

You can use std::next_permutation to compute all of the permutations of a sequence. It will look something like this:

std::array<int, 3> data = { 1, 2, 3 };
do {
    // use current permutation
} while (std::next_permutation(data.begin(), data.end()));

(I've used std::array from C++0x for this example; you can also find the array container in C++ TR1 and in Boost. This algorithm also works with any container that is bidirectionally iterable, like std::vector.)

Upvotes: 7

Related Questions