How to write a recursive function to generate all permutations of a string in VB.NET

1 Answer

0 votes
Imports System

Module PermuteString
    ' Swap characters in a character array
    Sub Swap(ByRef a As Char, ByRef b As Char)
        Dim temp As Char = a
        a = b
        b = temp
    End Sub

    ' Recursive function to generate permutations
    Sub generatePermutation(ByRef str() As Char, ByVal l As Integer, ByVal r As Integer)
        If l = r Then
            Console.WriteLine(New String(str))
        Else
            For i As Integer = l To r
                Swap(str(l), str(i))
                generatePermutation(str, l + 1, r)
                Swap(str(l), str(i)) ' backtrack
            Next
        End If
    End Sub

    Sub Main()
        Dim s As String = "ABC"
	
        Dim chars() As Char = s.ToCharArray()
	
        generatePermutation(chars, 0, chars.Length - 1)
    End Sub

End Module


 
' run:
' 
' ABC
' ACB
' BAC
' BCA
' CBA
' CAB
' 

 



answered Nov 5 by avibootz
...