String Permutation Generator
From yesterday's .NET Internal Meeting (dIM): Generate a list of permutation of a string, optimize for speed and space. Here's the code:
Dim inputString As String = Console.ReadLine
For x As Long = 0 To Math2.Factorial(inputString.Length) - 1
Dim outputstring As String() = New String(inputString.Length) {}
Dim outputInteger As Integer() = _
Math2.Permutation(inputString.Length, x)
For y As Integer = 0 To outputInteger.Length - 1
outputstring(y) = inputString(outputInteger(y))
Console.Write(outputstring(y))
Next
Console.WriteLine()
Next x
I need to use two functions not available in System.Math, so I’ve extended to System.Math2, containing two functions; Factorial and Permutation. Factorial is a standard recursive multiplication, while Permutation uses a more advanced technique. I stumbled on this technique while doing a small simulation project (where a random permutation of 20 elements was needed). Got it from MSDN, the link? Go find it yourself…
Using Permutation function, I need to enter two arguments, the number of elements, and the permutation “ID” to return.
Finally, it is just a matter of conversion between integers and characters (the original Permutation function is designed for a series of integers, not characters).
You’ll need the Permutation function to run the code above. Drop me a comment if you need it (or unsuccessful looking for it on MSDN)!