There is an array of letters ABCGD . It is necessary to find all variants of permutations, i.e. AB , AB , ABC , AVDG , ABCD , from two to five (in this case) characters.

I tried to use std::next_permutation , but this is not exactly what is required, since, for example, with three characters, it displays only three-character combinations.

I decided this when the output, but there was a new problem. As soon as two asterisks appear in the array (which is also necessary under the conditions of the problem), std::next_permutation stops working. What could be the problem and how to solve it?

 int Fact(int n) { if (n == 2 || n == 1) { return n; } else { return n * Fact(n - 1); } } void PrintC(char*arr, int len, int ind) { for (int i = 0; i < len; ++i) { cout << arr[i]; } cout << '\t'; for (int i = 2; i < len; i++) { if (len > 1 && ind % Fact(len - i) == 0) { PrintC(arr, len - 1, ind); } } } int len = 3; char* arr = new char[len + 1]; cin.getline(arr, len + 1); sort(&arr[0], &arr[len]); int ind = 1; do { cout << ind << endl << endl; PrintC(arr, len, ind); cout << endl; ind++; } while (next_permutation(&arr[0], &arr[len])); _getch(); return; 
  • one
    The task is more like building a powerful set (power set) than a permutation. next_permutation deals exactly with that permutations. - ixSci
  • Those. perhaps it is worth finding all the subsets with a certain number of elements and then rearranging the elements into them? Anyway, what’s the problem with next_permutation? Let's just say it should be so or was it somewhere I was mistaken? - Tropuc
  • 2
    Well, my task is not completely clear to me, but it seems that you need placements , and not permutations. This, in general, is solved by constructing a powerful set in which, then, permutations are already used on each subset that contains more than one element. There next_permutation no problems with next_permutation , just this function is intended for permutations, not for placements. - ixSci

1 answer 1

You can create a bit mask [0,0,1], [0,1,1], [1,1,1] (in this case, for three elements, the number of units is the number of output elements). While next_permutation => we go through the array and output the elements corresponding to one.

Of the minuses, the overhead memory.