learn permutation of string vb net

2020-05-06 14:23发布

问题:

i got an array of char and want to create a permutation with special condition

for example if i input 2, then it will generate permutation of 2 character the char array contains 6 elements like this inChars = {c,f,a,b,m,p)

when i run it with

3 character input, it generates, permutation of f,a,b

4 character --> f,a,b,m

my 1st question is why it begin from 2nd element of array (f) instead of (c)

and my 2nd questions how to create something like this: when i input 3 character, it will generate 2 and 3 subset of char instead of only 3 subset, it will be like

c,f

c-a

....

c,f,a

c,a,m

.....

here's the screenshot

here's the code

Public Class permute
Dim ItemUsed() As Boolean
Dim pno As Long, pString As String
Dim inChars() As Char = {"c", "f", "a", "b", "m", "p"}

Private Sub permute_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load  
End Sub

Sub Permute(ByVal K As Long)
    ReDim ItemUsed(K)
    pno = 0
    Permutate(K, 1)
    tb.Text = K
End Sub

Private Sub Permutate(ByVal K As Long, ByVal pLevel As Long)
    Dim i As Long, Perm As String
    Perm = pString

    For i = 1 To K
        If Not ItemUsed(i) Then
            If pLevel = 1 Then
                pString = inChars(i)
            Else
                pString += inChars(i)
            End If
            If pLevel = K Then
                pno = pno + 1
                Results.Text += _
                pno & " " & " = " & " " & pString & vbCrLf
                Exit Sub
            End If

            ItemUsed(i) = True
            Permutate(K, pLevel + 1)
            ItemUsed(i) = False
            pString = Perm
        End If
    Next
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Permute(tb.Text)
End Sub

Private Sub tb_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tb.TextChanged
    If tb.Text = "" Then
        Results.Text = ""
    Else
        Permute(tb.Text)
    End If
End Sub
End Class

回答1:

Change your For loop to start from 0 to K-1:

For i = 0 To K - 1

Update - second question

Sub Permute(ByVal K As Long)
    results = New List(Of String)
    ReDim ItemUsed(K)
    pno = 0

    Dim i As Integer
    For i = 2 To K
        Permutate(i, 1)
    Next
End Sub


标签: vb.net