Getting all combinations of numbers without repeating

hi I am working with C ++, can I find an easy way to get 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 is, if I get 5 or more numbers, how to make there 120 combinations

+3
source share
1 answer

These are permutations, not combinations.

You can use std::next_permutationto compute all 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 used std::arrayfrom C ++ 0x for this example, you can also find the container arrayin C ++ TR1 and Boost. This algorithm also works with any container that has bidirectional iterability, for example std::vector.)

+7

Source: https://habr.com/ru/post/1784454/


All Articles