Search code examples
vb.netstringrandomkey-generator

Key gen random number issue


I am in need of a Random number generator in the following format: 65X XXX XXXX ; excluding 1 & 4. This is the final step before im finished my first VB.net project. Please respond if you can help.

Below is my currant code that works great other than it not excluding digits. If you could please help edit my code I would be ever so grateful.. Thank you!

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

Dim rnd As New Random
Dim str1, str2, str3 As String
str1 = "65" & rnd.Next(0, 9)
str2 = rnd.Next(100, 999)
str3 = rnd.Next(1000, 9999)
ListBox1.Items.Add(str1 & " " & str2 & " " & str3)
End Sub

Solution

  • Create one random generator instead of creating a new one on each timer click. The random generator is seeded with a value created from the system clock, so if you create them too close in time they will generate the same series of random numbers. Also, creating them at a set interval might produce unwanted patterns in the random numbers.

    Private rnd As New Random
    

    You can use a function that creates a random string from a specific set of characters:

    Private Function RandomString(ByVal chars As String, ByVal len As Integer) As String
      Dim result As String = ""
      For i As Integer = 1 to len
        result += chars.Substring(rnd.Next(chars.Length), 1)
      Next
      Return result
    End Function
    

    (Note: Using += to concatenate strings should only be used for short strings. For anything longer than about 20 characters you should use a StringBuilder or a character array instead.)

    Now you can use the function to create the string:

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
      Dim chars As String = "02356789"
      Dim str As String = "65" & _
        RandomString(chars, 1) & " " & _
        RandomString(chars, 3) & " " & _
        RandomString(chars, 4)
      ListBox1.Items.Add(str)
    End Sub