Is it more efficient to begin with a possibly random ordering of objects in a range, using next_permutation to step through all greater permutations, followed by stepping down, beginning again with the original ordering, using prev_permutation to reach the last.
Or, to sort the range before permuting, then to use only next_permutation to step through all of them?
next_permutation will step through all permutations, not only through greater permutations. No need to revert and use prev_permutation, and certainly no need to sort.
You only need take care of the fact that next_permutation will return false once it “rolls over” into the lexicographically lowest permutation so you need to keep track of the number of the current permutation to know when to stop.
That is, the following will iterate through all possible permutations of a range, no matter how the starting range looks like.
size_t const num_permutations = multinomial_coefficient(range);
for (size_t i = 0; i < num_permutations; ++i) {
next_permutation(range.begin(), range.end());
// use permutation.
}
Where multinomial_coefficient is the multinomial coefficient of the number of distinct elements in the range. In the simple case where all elements are distinct, this is equivalent to N!, the factorial of the number of elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With