How to generate all possible permutations and combinations of an array of chars in VB.NET

1 Answer

0 votes
Imports System

Public Class PermutationsAndCombinations

    ' Swap two characters in an array
    Private Shared Sub Swap(arr As Char(), i As Integer, j As Integer)
        Dim tmp As Char = arr(i)
        arr(i) = arr(j)
        arr(j) = tmp
    End Sub

    ' Print array of chars
    Private Shared Sub PrintArray(arr As Char(), size As Integer)
        For i As Integer = 0 To size - 1
            Console.Write(arr(i) & " ")
        Next
        Console.WriteLine()
    End Sub

    ' Recursive function to generate permutations
    Private Shared Sub Permute(arr As Char(), l As Integer, r As Integer)
        If l = r Then
            PrintArray(arr, r + 1)
            Return
        End If

        For i As Integer = l To r
            Swap(arr, l, i)
            Permute(arr, l + 1, r)
            Swap(arr, l, i) ' backtrack
        Next
    End Sub

    ' Generate all combinations using bitmask
    Private Shared Sub GenerateCombinations(arr As Char(), size As Integer)
        For mask As Integer = 1 To (1 << size) - 1
            For i As Integer = 0 To size - 1
                If (mask And (1 << i)) <> 0 Then
                    Console.Write(arr(i) & " ")
                End If
            Next
            Console.WriteLine()
        Next
    End Sub

    Public Shared Sub Main(args As String())
        Dim input As Char() = {"a"c, "b"c, "c"c}
        Dim size As Integer = input.Length

        Console.WriteLine("All permutations:")
        Permute(input, 0, size - 1)

        Console.WriteLine(Environment.NewLine & "All combinations:")
        GenerateCombinations(input, size)
    End Sub

End Class



' run:
' 
' All permutations:
' a b c 
' a c b 
' b a c 
' b c a 
' c a b 
' c b a 
' 
' All combinations:
' a 
' b 
' a b 
' c 
' a c 
' b c 
' a b c 
' 

 



answered 16 hours ago by avibootz

Related questions

...