Results 1 to 10 of 10

Thread: Loops in vb.net

  1. #1

    Thread Starter
    New Member
    Join Date
    Jun 2014
    Posts
    3

    Loops in vb.net

    I have a code that loop from A to D and displays the result in a text box as the loop continues.

    Code:
    Dim test(0 To 3) As String
    
    test(0) = "A"
    test(1) = "B"
    test(2) = "C"
    test(3) = "D"
    
    For i As Int32 = 0 To test.Length - 1
        TextBox4.Text = test(i)
        TextBox4.Refresh()
        Me.Refresh()
    Next
    But the problem is that the loop only goes like A , B , C ,D
    How can I make the loop so it keep going on like
    A
    B
    C
    D
    AA
    AB
    AC ....and so on?
    Last edited by dday9; Jun 26th, 2014 at 10:10 AM. Reason: Added code tags

  2. #2
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,760

    Re: Loops in vb.net

    I've added code tags to your code for you to keep the formatting. Those look like this:
    [code]'My code here[/code]

    There are a couple of things that I notice. The first is how you're declaring the upper bounds of your array. Rather than typing:
    Code:
    Dim test(0 To 3) As String
    Simplify it by typing this:
    Code:
    Dim test(3) As String
    As to your issue at hand. You want to create a nested loop:
    Code:
    Dim test() As String = {"A", "B", "C", "D"}
    
    For x As Integer = 0 To test.Length - 1
        'Print out either: A, B, C, or D
        Console.WriteLine(test(x))
        For y As Integer = 0 To test.Length - 1
            'Print out: AA, AB, AC, etc.
            Console.WriteLine(test(x) & test(y))
        Next
    Next
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  3. #3

    Thread Starter
    New Member
    Join Date
    Jun 2014
    Posts
    3

    Re: Loops in vb.net

    Thank you so much. I asked this on so many forums and you are the only one who gave a thorough reply.
    Also, I tired this code and it worked for 2 alphabets. Should I keep nesting in more and more loops if I were to loop till say, 8 alphabets?

  4. #4
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,760

    Re: Loops in vb.net

    Well it depends. If you want 8 letters, then you would only add the letters to your array. If you wanted more letter combinations(ie: ABA, DABB, etc.) then you would add more nested loops.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  5. #5

    Thread Starter
    New Member
    Join Date
    Jun 2014
    Posts
    3

    Re: Loops in vb.net

    Yes I meant combinations. Well that makes sense now. I have just one last concern. I changed the text box code to:
    TextBox4.Text = test(x) & test(y) & test(z)
    I know the code is testing x, then x & y, x & y & z... but the text box will only show the test(x) & test (y) AKA just the 2 letter combinations.
    Is there a way to fix that?

  6. #6
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: Loops in vb.net

    Quote Originally Posted by Ramiroapollo View Post
    Should I keep nesting in more and more loops if I were to loop till say, 8 alphabets?
    Well, let's think about this. Dop we know ahead of time how many letters we want to loop up to? If we do, can we imagine a function that does it? I'm going to suppose there is a method we can call that returns an IEnumerable(Of String), and use a For Each loop over that result rather than embedding the generation logic in the loop:

    vbnet Code:
    1. Module Module1
    2.     Sub Main()
    3.         For Each letterString As String In GetStringsUpToLength(8)
    4.             Console.WriteLine(letterString)
    5.         Next
    6.         Console.ReadLine()
    7.     End Sub
    8. End Module

    So for every string that gets returned, we simply write it out to the console. So what could GetStringsUpToLength possibly look like? Well, if I suppose the existence of a method that returns me all the strings of exactly a given length, it's pretty easy - I simply loop from 1 to the desired length, and call that method for each of them, outputting each element in each of the result sets:

    vbnet Code:
    1. Private Iterator Function GetStringsUpToLength(length As Integer) As IEnumerable(Of String)
    2.         For currentLength = 1 To length
    3.             For Each letterString In GetStringsOfLength(currentLength)
    4.                 Yield letterString
    5.             Next
    6.         Next
    7.     End Function

    Note that this is an iterator function, which means we use Yield to return multiple results, each one becomes a single element in the returned sequence.

    So, we've got to write GetStringsOfLength now, and this time, I won't pass the buck to yet another method.

    What happens if I pass in, say 8? To get the strings of exactly 8, I first start with all the strings starting with "A", and each one is followed by a unique 7 letter string, then the ones starting with "B" followed by all the different 7 letter strings, then "C" followed by ... Gee, it sure would be handy to have a method that returns me all the unique 7 letter strings, wouldn't it? That'd make this method a lot easier. Wait, that's exactly the method I'm writing!

    So what happens when we pass in 1? We want "A" followed by all the 0 length strings, then "B" followed by all the 0 length strings, ... which suggests that if we pass in 0 (or less?), we should return a single element that is the empty string, otherwise we recurse. It ends up looking like this:

    vbnet Code:
    1. Private Iterator Function GetStringsOfLength(length As Integer) As IEnumerable(Of String)
    2.         If length < 1 Then
    3.             Yield String.Empty
    4.             Return
    5.         End If
    6.  
    7.         For Each letter In _letters
    8.             For Each shorterString In GetStringsOfLength(length - 1)
    9.                 Yield letter + shorterString
    10.             Next
    11.         Next
    12.     End Function

    Whole thing:

    vbnet Code:
    1. Module Module1
    2.  
    3.     Sub Main()
    4.         For Each letterString As String In GetStringsUpToLength(3)
    5.             Console.WriteLine(letterString)
    6.         Next
    7.         Console.ReadLine()
    8.     End Sub
    9.  
    10.     Private Iterator Function GetStringsUpToLength(length As Integer) As IEnumerable(Of String)
    11.         For currentLength = 1 To length
    12.             For Each letterString In GetStringsOfLength(currentLength)
    13.                 Yield letterString
    14.             Next
    15.         Next
    16.     End Function
    17.  
    18.     Private Iterator Function GetStringsOfLength(length As Integer) As IEnumerable(Of String)
    19.         If length < 1 Then
    20.             Yield String.Empty
    21.             Return
    22.         End If
    23.  
    24.         For Each letter In _letters
    25.             For Each shorterString In GetStringsOfLength(length - 1)
    26.                 Yield letter + shorterString
    27.             Next
    28.         Next
    29.     End Function
    30.  
    31.     Private _letters() As String = {"A", "B", "C", "D"}
    32.  
    33. End Module

  7. #7
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,043

    Re: Loops in vb.net

    If you know that you always want X letters in the final result, and X is a fairly small number, then nested loops would be an efficient way to go. However, if the number of letters you want is arbitrary, then nested loops isn't possible. Further, if the number of letters (X) is large, then nested loops will quickly become fairly difficult.

    One solution would be to use recursion and a List(of Strings). This will work up to a point, but since recursion means the function keeps calling itself over and over, then if X gets high enough, the program will crash with a StackOverflow exception. A non-recursive loop would be better, but you have to keep in mind that you are talking about combinations, which means that both the time taken and the memory consumed will increase exponentially. To create such a thing, you might do something like this:

    Code:
    Private test() As String = {"A", "B", "C", "D"} 
    
    
    Private Function FillList(curList As List(of String)) As List(of String)
      Dim ret As New List(of String)
    
      For Each st1 in curList
       For Each chr In test
        ret.Add(st1 & chr)
       Next
     Next
    
     Return ret
    End Function
    
    'This would be used in a method like this:
    
    Public Function BuildList(numberOfIterations As Integer) As List(of String)
     Dim ret As New List(of String)
     
     'The set has to be added one time to start out with.
     ret.AddRange(test)
    
     For x = 1 to numberOfIterations
      ret = FillList(ret)
     Next
    
     Return ret
    End Function
    This was written freehand without any testing, so something may be slightly off, but the general idea is pretty sound. This will gag even the best computer if numberOfIterations is large enough, because of the exponential rise in cost.
    My usual boring signature: Nothing

  8. #8
    Frenzied Member Gruff's Avatar
    Join Date
    Jan 2014
    Location
    Scappoose Oregon USA
    Posts
    1,293

    Re: Loops in vb.net

    This was my take on it.
    It uses a recursive function
    Code:
    Public Class Form1
      Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        'Test for two to three letter return 
        Dim s As String = ""
        For i = 695 To 705
          s &= LetterEncode(i) & Environment.NewLine
        Next
        MessageBox.Show(s)
      End Sub
    
      Function LetterEncode(Number As Int32) As String
        'Recursive Function
        If Convert.ToBoolean(Number) Then
          Dim CurrentLetter = Convert.ToChar(65 + (Number - 1) Mod 26)
          Dim ReducedValue = (Number - 1) \ 26
          Return LetterEncode(ReducedValue) & CurrentLetter
        Else
          Return ""
        End If
      End Function
    End Class
    Burn the land and boil the sea
    You can't take the sky from me


    ~T

  9. #9
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: Loops in vb.net

    A big advantage of using sequences, as in my suggestion, is that you don't have to calculate the entire list before starting to work on the first element, and once you've finished working with an element it is free to be collected by GC, putting far less memory pressure on the system - with a list containing all the values, you need to store the entire list in memory for the entire duration of the loop.

    Also, if you potentially want to "keep going" until some condition is met, it is trivial to convert the sequence generated to an infinite one that keeps supplying letters strings until you ask it to stop, you don't need to know how many you'll need. I'd highly recommend thinking in terms of sequences if at all possible.

  10. #10
    Frenzied Member Gruff's Avatar
    Join Date
    Jan 2014
    Location
    Scappoose Oregon USA
    Posts
    1,293

    Re: Loops in vb.net

    All very good points.

    I guess I couldn't envision anyone needing to run beyond four or five characters.

    I use to use this sort of thing to shorten and encode serial numbers for product labels.
    The product was a tiny gold plated probe for silicon wafers.
    The area for the label was extremely small and even with a small font you couldn't get much on them.

    If memory serves compressing them this way allowed slightly over 12.3 million within five letters.
    Last edited by Gruff; Jun 26th, 2014 at 07:09 PM.
    Burn the land and boil the sea
    You can't take the sky from me


    ~T

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width