Home > database >  How to use Nested Loop in Visual Basic for all unrepeated combinations of characters?
How to use Nested Loop in Visual Basic for all unrepeated combinations of characters?

Time:09-29

I am trying to get the combinations of all possible unrepeated character sets from the user input. As I am just beginning to learn the programming, it is obvious that I don't properly understand how those nested loops work. Here is my code:

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ListBox1.Items.Clear()
        Dim c1 As String = TextBox1.Text
        Dim i, j As Integer
        Dim str As String()
        Dim k As Integer = 0
        For i = 0 To c1.Length - 1
            For j = 0 To i
                ListBox1.Items.Add(c1(i) & c1(j))
            Next
        Next
    End Sub
End Class

As you can see in the picture attached, I cannot get the rest. How can I get the character pairs I put in the red box on notepad? Can someone help me, please.enter image description here

CodePudding user response:

You had the right idea. However, expand your logic so that for every letter of the outer loop you spin through every letter again. And if you don't want repeated letter pairs, add an If statement:

For i = 0 To c1.Length - 1
   For j = 0 To c1.Length - 1
      If i <> j Then ListBox1.Items.Add(c1(i) & c1(j))
   Next
Next
  • Related