There are also the operators I contributed to the MoreLinq project on Google Code in the EvenMoreLinq
branch. If you're just curious about how the algorithm is implemented, you can see the code for Permutations<T>()
here.
They are designed to blend well with LINQ, and use both deferred and streaming evaluation. Permutations is an interesting one, since generating all permutations is a N!
operation ... which becomes very large for even small values of N
. Depending on how you generate permutations, you may (or may not) be able to actually enumerate them all.
You'll also find algorithms for other combinatoric operations (Subsets, PermutedSubsets, Cartesian Products, Random Subsets, Slices, Partitions, etc) in that same codebase.
Here's how you can use the MoreLinq extensions to permute a sequence. So for instance, you could permute a string (which is treated as a sequence of char
s) as follows:
using MoreLinq;
string input = "cat";
var permutations = input.Permutations();
foreach( var permutation in permutations )
{
// 'permutation' is a char[] here, so convert back to a string
Console.WriteLine( new string(permutation) );
}