Print all permutations of a string in vb.net

Vb program for Print all permutations of a string. Here problem description and other solutions.

' Include namespace system
Imports System 
'  Vb.net program for
'  Print all permutations of a string
public Class Permutation
    '  Swapping two string elements by index
    Public Function  swap(ByVal text As String, 
                          ByVal size As Integer, 
                          ByVal a As Integer, 
                          ByVal b As Integer) As String
        '  Check valid location of swap element
        if ((a >= 0 AndAlso a < size) AndAlso 
            (b >= 0 AndAlso b < size)) Then
            '  Get first character
            Dim first As Char = text(a)
            '  Get second character
            Dim second As Char = text(b)
            '  Put character
            text = text.Substring(0,b-0) + first.ToString() + 
              text.Substring(b + 1)
            text = text.Substring(0,a-0) + second.ToString() + 
              text.Substring(a + 1)
        End If
        Return text
    End Function
    '  Method which is print all permutations of given string
    Public Sub findPermutation(ByVal text As String, 
                               ByVal n As Integer, 
                               ByVal size As Integer)
        if (n > size) Then
            Return
        End If
        if (n = size) Then
            Console.WriteLine(text)
            Return
        End If
        Dim i As Integer = n
        While i < size
            '  Swap the element
            text = Me.swap(text, size, i, n)
            Me.findPermutation(text, n + 1, size)
            '  Swap the element
            text = Me.swap(text, size, i, n)
        i += 1
        End While
    End Sub
    Public Shared Sub Main(ByVal args As String())
        Dim task As Permutation = New Permutation()
        Dim text As String = "ABC"
        Dim size As Integer = text.Length
        task.findPermutation(text, 0, size)
        Console.WriteLine()
        text = "abcd"
        size = text.Length
        task.findPermutation(text, 0, size)
    End Sub
End Class

Output

ABC
ACB
BAC
BCA
CBA
CAB

abcd
abdc
acbd
acdb
adcb
adbc
bacd
badc
bcad
bcda
bdca
bdac
cbad
cbda
cabd
cadb
cdab
cdba
dbca
dbac
dcba
dcab
dacb
dabc


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved