3

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

James McNellis
  • 348,265
  • 75
  • 913
  • 977
duaa
  • 31
  • 2
  • 1
    What you're looking for is something called the "powerset" and thus this is a duplicate of [combinations algorithm](http://stackoverflow.com/questions/2506119/combinations-algorithm) – Mark Elliot Jan 10 '11 at 03:31
  • 2
    @Mark: Based on the OP's example and numbers, I think he actually means _permutations_, not _combinations_. (I'm certain there is a duplicate, but a quick 30 second search didn't yield one.) – James McNellis Jan 10 '11 at 03:34
  • possible duplicate of [How do I get all permutations of xPy in C?](http://stackoverflow.com/questions/1663949/how-do-i-get-all-permutations-of-xpy-in-c) – Greg Hewgill Jan 10 '11 at 03:36
  • @James, you're right, though I'm sure this is still a duplicate, but I must have the wrong one. – Mark Elliot Jan 10 '11 at 03:37

1 Answers1

7

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.)

James McNellis
  • 348,265
  • 75
  • 913
  • 977