GENERATING UNIQUE RANDOM STRING AND ITS APPLICATION

Generating random numbers can be sometimes frustrating, especially when you want them to be unique.

Example in this instance is when you give users unique usernames when they register with you websites.

Below is a simple function to generate random numbers. To make these generated random strings unique (for the purpose of your application you can add the row index, when inserting it into a database, to make it unique. In this case you will be generating always unique random variables)

Function Generate() As String
‘key_chars, is the length of random numbers u want to generate

Dim i_key As Integer

Dim RandomNo As Single
Dim arrIndex As Int16

Dim sb As New StringBuilder

Dim RandomLetter As String

lstLetters = "abcdefghijklmnopqrstuvwxyz"

lstNumber = "0123456789"

LettersArray = Me.Key_Letters.ToCharArray

NumbersArray = Me.lstNumber.ToCharArray


For i_key = 1 To Key_Chars

Randomize()

RandomNo = Rnd()

arrIndex = -1 ‘the number 101 was randomly chosen

If (CType(Random1 * 101, Integer)) Mod 2 = 0 Then

‘if the number generated from the if condition is even get a letter else get a number

‘ generate a random number from the letters array


Do While arrIndex < 0

arrIndex = Convert.ToInt16(LettersArray.GetUpperBound(0) * RandomNo)

Loop

RandomLetter = LettersArray(arrIndex)

sb.Append(RandomLetter)

Else

Do
While arrIndex < 0

arrIndex = Convert.ToInt16(NumbersArray.GetUpperBound(0) * RandomNo)

Loop

RandomLetter = NumbersArray(arrIndex)

sb.Append(RandomLetter)

EndIf

Next

Return sb.ToString

End Function

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s