I think I managed to adapt HeapPermute algorithm and make a generic class out of it.
Some theory can be found here:
http://www.cut-the-knot.org/do_you_know/AllPerm.shtml
vb Code:
''' <summary> ''' A generic class that encapsulates a HeapPermute algorithm (I think) ''' </summary> ''' <typeparam name="T"></typeparam> ''' <remarks> ''' With this class you can obtain an IEnumerable which contains all the permutations of the given sequence of values. ''' </remarks> Class Permuter(Of T) ' VS 2010 Auto implemented Public Property Sequence As IEnumerable(Of T) Public Function GetAllPermutations() As IEnumerable(Of IEnumerable(Of T)) Return GetAllPermutations(_Sequence) End Function Private Function GetAllPermutations(ByVal values As IEnumerable(Of T)) As IEnumerable(Of IEnumerable(Of T)) Dim ret As New List(Of List(Of T)) Select Case values.Count Case 0 Return ret Case 1 ret.Add(New List(Of T) From {values(0)}) Return ret Case Else Dim GetExcluded = Function(sourcevalues As IEnumerable(Of T), excluded_element As T) As IEnumerable(Of T) Return From vals In sourcevalues Where Not vals.Equals(excluded_element) End Function For Each value As T In values Dim tempret As IEnumerable(Of IEnumerable(Of T)) = GetAllPermutations(GetExcluded(values, value)) For Each tempelement In tempret Dim templist As New List(Of T) templist.Add(value) templist.AddRange(tempelement) ret.Add(templist) Next Next Return ret End Select End Function End Class
Test program:
vb Code:
Sub Main() Dim p As New Permuter(Of Integer) Dim sequence() As Integer = {1, 2, 3, 4} p.Sequence = sequence Dim ret As IEnumerable(Of IEnumerable(Of Integer)) = p.GetAllPermutations For Each permutedsequence In ret For Each value As Integer In permutedsequence Console.Write(value.ToString & "; ") Next Console.WriteLine() Next Console.ReadLine() End Sub
Test output:
Code:1; 2; 3; 4; 1; 2; 4; 3; 1; 3; 2; 4; 1; 3; 4; 2; 1; 4; 2; 3; 1; 4; 3; 2; 2; 1; 3; 4; 2; 1; 4; 3; 2; 3; 1; 4; 2; 3; 4; 1; 2; 4; 1; 3; 2; 4; 3; 1; 3; 1; 2; 4; 3; 1; 4; 2; 3; 2; 1; 4; 3; 2; 4; 1; 3; 4; 1; 2; 3; 4; 2; 1; 4; 1; 2; 3; 4; 1; 3; 2; 4; 2; 1; 3; 4; 2; 3; 1; 4; 3; 1; 2; 4; 3; 2; 1;




Reply With Quote