I would like to generate all permutations of a collection (collection), for example:
Collection: 1, 2, 3 Permutations: {1, 2, 3} {1, 3, 2} {2, 1, 3} {2, 3, 1} {3, 1, 2} {3, 2, 1}
This is not a question of how, in general, but more about how it is most effective. In addition, I would not want to generate all permutations and return them, but only generated a single permutation at a time and continued only if necessary (like the Iterators, which I also tried, but turned out to be less efficient).
I tested a lot of algorithms and approaches and came up with this code, which is the most effective of those that I tried:
public static bool NextPermutation<T>(T[] elements) where T : IComparable<T> {
This usage will send an array of elements and return a boolean value indicating whether it was the last lexicographic permutation or not, as well as changing the array to the next permutation.
Usage example:
var arr = new[] {1, 2, 3}; PrintArray(arr); while (!NextPermutation(arr)) { PrintArray(arr); }
The thing is, I'm not happy with the speed of the code.
Iterating over all permutations of an array of size 11 takes about 4 seconds. Although this can be considered impressive, since the number of possible permutations of the set of sizes 11 is 11! , which is about 40 million.
Logically, with an array of size 12 it will take about 12 times more time, since 12! - 11! * 12 11! * 12 , and with an array of size 13 it will take about 13 times more time than the time spent on size 12, etc.
So, you can easily understand how using an array of 12 or more in size takes a lot of time to go through all the permutations.
And I have a strong hunch that I can somehow reduce the time (without switching to a language other than C #), because compiler optimizations really optimize quite nicely, and I doubt that I could optimize as well, manually, in Installation).
Does anyone know of any other way to do this faster? Do you have any ideas on how to run the current algorithm faster?
Please note that I do not want to use an external library or service for this - I want to have the code itself, and I want it to be as efficient as humanly possible.
Thank you for reading everything! :)