Imports System
Imports System.Collections.Generic
Public Class PermutationsAndCombinations
' Print a list of characters
Private Shared Sub PrintList(list As List(Of Char))
For Each ch As Char In list
Console.Write(ch & " ")
Next
Console.WriteLine()
End Sub
' Generate all permutations in lexicographic order
Private Shared Sub GeneratePermutations(list As List(Of Char))
list.Sort() ' Ensure lexicographic order
Do
PrintList(list)
Loop While NextPermutation(list)
End Sub
' Implementation of next_permutation (like C++ STL)
Private Shared Function NextPermutation(list As List(Of Char)) As Boolean
Dim size As Integer = list.Count
Dim i As Integer = size - 2
While i >= 0 AndAlso list(i) >= list(i + 1)
i -= 1
End While
If i < 0 Then Return False
Dim j As Integer = size - 1
While list(j) <= list(i)
j -= 1
End While
' Swap
Dim temp As Char = list(i)
list(i) = list(j)
list(j) = temp
' Reverse the suffix
list.Reverse(i + 1, size - (i + 1))
Return True
End Function
' Generate all combinations using bitmask
Private Shared Sub GenerateCombinations(list As List(Of Char))
Dim size As Integer = list.Count
For mask As Integer = 1 To (1 << size) - 1
Dim subset As New List(Of Char)()
For i As Integer = 0 To size - 1
If (mask And (1 << i)) <> 0 Then
subset.Add(list(i))
End If
Next
PrintList(subset)
Next
End Sub
Public Shared Sub Main(args As String())
Dim list As New List(Of Char) From {"a"c, "b"c, "c"c}
Console.WriteLine("All permutations:")
GeneratePermutations(New List(Of Char)(list))
Console.WriteLine(Environment.NewLine & "All combinations:")
GenerateCombinations(list)
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
'