SIMIN Posted January 17, 2009 Posted January 17, 2009 (edited) Hi, I wanna generate a random alphanumeric in the following format: d4g2o5m3-u1q2-s7z9-z6o8-o3q2c2m5m2s9 So with your help, I wrote a public function like this: Public Function GenerateContactID() As String Dim MyRandom As New Random GenerateContactID = Nothing For MyLoop As Integer = 1 To 8 If MyLoop Mod 2 = 1 Then GenerateContactID = GenerateContactID + Convert.ToChar(MyRandom.Next(97, 123)) End If If MyLoop Mod 2 = 0 Then GenerateContactID = GenerateContactID + MyRandom.Next(1, 10).ToString End If Next GenerateContactID = GenerateContactID + "-" For MyLoop As Integer = 1 To 4 If MyLoop Mod 2 = 1 Then GenerateContactID = GenerateContactID + Convert.ToChar(MyRandom.Next(97, 123)) End If If MyLoop Mod 2 = 0 Then GenerateContactID = GenerateContactID + MyRandom.Next(1, 10).ToString End If Next GenerateContactID = GenerateContactID + "-" For MyLoop As Integer = 1 To 4 If MyLoop Mod 2 = 1 Then GenerateContactID = GenerateContactID + Convert.ToChar(MyRandom.Next(97, 123)) End If If MyLoop Mod 2 = 0 Then GenerateContactID = GenerateContactID + MyRandom.Next(1, 10).ToString End If Next GenerateContactID = GenerateContactID + "-" For MyLoop As Integer = 1 To 4 If MyLoop Mod 2 = 1 Then GenerateContactID = GenerateContactID + Convert.ToChar(MyRandom.Next(97, 123)) End If If MyLoop Mod 2 = 0 Then GenerateContactID = GenerateContactID + MyRandom.Next(1, 10).ToString End If Next GenerateContactID = GenerateContactID + "-" For MyLoop As Integer = 1 To 12 If MyLoop Mod 2 = 1 Then GenerateContactID = GenerateContactID + Convert.ToChar(MyRandom.Next(97, 123)) End If If MyLoop Mod 2 = 0 Then GenerateContactID = GenerateContactID + MyRandom.Next(1, 10).ToString End If Next End Function However, sometimes the call to this function will return the same result, I mean it's not completely random? How that's possible? Thank you :) Edited January 18, 2009 by SIMIN Quote
Administrators PlausiblyDamp Posted January 18, 2009 Administrators Posted January 18, 2009 Not properly tested but I would have written it as Dim r As New Random Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim GenerateContactID As String = String.Empty For MyLoop As Integer = 1 To 8 If MyLoop Mod 2 = 1 Then GenerateContactID &= Convert.ToChar(r.Next(97, 122)) Else GenerateContactID &= r.Next(0, 9).ToString() End If Next Debug.WriteLine(GenerateContactID) End Sub Although things like CInt etc. are perfectly valid in .Net I tend to avoid them simply because I use both C# and VB.Net and remembering two ways to do things is twice the effort of remembering one way ;) Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.