[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1022
  • Last Modified:

Generate 20 character random string of data

I'd like to build a random 20 character string for an application I'm writing in VB6. How would I do this so it gives me only numbers 0-9 or letters A-Z? I need it to be 20 positions long with only these values above.

A snippet of code would be great folks!

Thanks.
0
samic400
Asked:
samic400
  • 4
  • 3
  • 2
  • +2
2 Solutions
 
FER_GCommented:
samic400; a very easy way is the next code... of course there be anothers ways to get it, but this is very easy to understand...


FerG
--
Saludos
Ing. Fernando D. Giletta
San Francisco. Córdoba. Argentina
Public Function NroAleatorio_Entero(valorInferior As Double, valorSuperior As Double, _
Optional iniciarSemilla As Boolean = False) As Double
'Este metodo devuelve un NRO ALEATORIO entre los 2 limites.
    NroAleatorio_Entero = Int(NroAleatorio_Decimal(valorInferior, valorSuperior, iniciarSemilla))
End Function
 
Public Function NroAleatorio_Decimal(valorInferior As Double, valorSuperior As Double, _
Optional iniciarSemilla As Boolean = False) As Double
'Este metodo devuelve un NRO ALEATORIO entre los 2 limites.
    If (iniciarSemilla) Then
        Randomize Timer
    End If
    NroAleatorio_Decimal = ((valorSuperior - valorInferior + 1) * Rnd + valorInferior)
End Function
 
 
Private Function randomChar(CharLen As Long) As String
    Dim I As Long
    Dim value As Long
    Randomize
    
    For I = 1 To CharLen
        value = NroAleatorio_Entero(1, 3)
        Select Case value
            Case Is = 1: value = NroAleatorio_Entero(65, 90)  ' [A-Z]
            Case Is = 2: value = NroAleatorio_Entero(97, 122) ' [a-z]
            Case Is = 3: value = NroAleatorio_Entero(48, 57)  ' [0-9]
        End Select
        randomChar = randomChar & Chr(value)
    Next
End Function
 
Private Sub cmd1_Click()
    MsgBox "Cadena aleatoria: " & randomChar(20)
End Sub

Open in new window

0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Another one...
Option Explicit
 
Private Sub Command1_Click()
    Dim word As String
    word = GetRandomWord(20)
    Debug.Print word
End Sub
 
Private Function GetRandomWord(ByVal length As Integer) As String
    Static rndFlag As Boolean
    If Not rndFlag Then
        rndFlag = True
        Randomize
    End If
    Dim i As Integer
    Dim pickFrom As String
    pickFrom = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    For i = 1 To length
        GetRandomWord = GetRandomWord & Mid(pickFrom, Len(pickFrom) * Rnd + 1, 1)
    Next i
End Function

Open in new window

0
 
aikimarkCommented:
Please read my article on this:
http://www.15seconds.com/issue/051110.htm

You need to be aware that the VB PRNG functions (Randomize and Rnd) have some limitations that can produce 'collisions' -- duplicate random number sequences.

The code snippet supplied by Idle_Mind is the method for translating random number sequences into character strings.

Depending on your uniqueness and performance requirements, you might need to tweak that code.

1. How many of these 20 character strings do you need to produce?
2. Do these strings need to be unique?
3. Are there any time constraints on the execution of this process?
4. What about lower case a-z characters?
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
samic400Author Commented:
aikimark - to answer your questions:

1. How many of these 20 character strings do you need to produce? probably just one at any given time.

2. Do these strings need to be unique? yes. my thought was the more characters to choose from, the more unique the string would be.

3. Are there any time constraints on the execution of this process? not really.

4. What about lower case a-z characters? yes, I can use lower case if it helps define the uniqueness of the string.
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
With regard to uniqueness...if you need to ABSOLUTELY prevent duplicates then you'd need to store all previously generated values in a database of some sort and check if the currently generated value already exists there.

If you give more details about HOW the sequences will be used then we can give better implementation advice.
0
 
samic400Author Commented:
My application will be used to store a customer number and this key in a database for later use. It will be used in a web page so some hacker cannot identify what it represents and when it comes back to my web site as a parameter, I can look up in my database and know what customer number they are referring to so being unique is critical.
0
 
samic400Author Commented:
The database will be SQL Server.
0
 
aikimarkCommented:
Given the PRNG weakenesses, using the a-z (lower case) characters will not ensure uniqueness.  You have to compensate for the weaknesses in the VB development environment.

If you read my article, you now know that the biggest weakness of the VB PRNG functions is the limited number of unique seeds produced by the Randomize statement.

If you are generating these for a row in your database, you should probably include the autonumber primary key value in a calculation that augments the Rnd values.

=================
My recommendations:
1. Use the same seed value for all the Randomize functions
2. Use a loop to move the PRNG sequence forward = CLng(Date())
3. Generate your own sequence by multiplying the row ID value (autonumber) by the Rnd() value, add the CLng(Date()) value, and then use the MOD 36 of that value as the index into your character string.

Notes:
* Use Mod 62 if you add the lower case a-z characters.
* If you don't have an autonumber row ID, then use the Timer()*100 value.
* If you add these modifications to the Rnd values, then a-z WILL increase the likelihood of unique strings.
Idle_Mind is correct that you should add a unique index on this 'random' column in the table where these values will be stored.

See example in the snippet.  This does not use the autonumber value, since I don't know that part of your application.

Private Function GetRandomWord(ByVal parmlength As Integer) As String
    Dim lngDays As Long
    Dim i As Long
    Dim lngTime As Long
    Const pickFrom As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    Dim pickLen As Long
 
    pickLen = Len(pickFrom)
    lngDays = CLng(Date)
    lngTime = Timer * 100
 
    Rnd -1
    Randomize lngDays 
    For i = 1 to lngDays 
       Rnd
    Next
 
    For i = 1 To parmlength
        GetRandomWord = GetRandomWord & Mid(pickFrom, ((lngTime * Rnd) + lngDays) Mod pickLen + 1, 1)
    Next i
 
End Function

Open in new window

0
 
VKCommented:
The GetID-function below bases upon the GUID-Generator of Windows, which is really
random and the probability to get duplicates is extremly improbable.
Because the CreateGUID-function generates a 32 character Hex-String and i needed
a 20 character string with the same improbability, i wrote a wrapper which contverts the
32 char. Hex-String into a typeable 20 character string. It was not possible to maintain
the same improbability without incuding characters to your set (0-9 or letters A-Z).
The ouput of GetID is a string contaning 20 characters (ASCII 33 to126) which are typeable.
Private Type GUID
     Data1 As Long
     Data2 As Long
     Data3 As Long
     Data4(8) As Byte
End Type
 
Private Declare Function CoCreateGuid Lib "ole32.dll" (pguid As GUID) As Long
Private Declare Function StringFromGUID2 Lib "ole32.dll" (rguid As Any, ByVal lpstrClsId As Long, ByVal cbMax As Long) As Long
 
Private Function CreateGUID(Optional strRemoveChars As String = "{}-") As String
    Dim udtGUID As GUID
    Dim strGUID As String
    Dim bytGUID() As Byte
    Dim lngLen As Long
    Dim lngRetVal As Long
    Dim lngPos As Long
 
    'Initialize
    lngLen = 40
    bytGUID = String(lngLen, 0)
 
    'Create the GUID
    CoCreateGuid udtGUID
 
    'Convert the structure into a displayable string
    lngRetVal = StringFromGUID2(udtGUID, VarPtr(bytGUID(0)), lngLen)
    strGUID = bytGUID
    If (Asc(Mid$(strGUID, lngRetVal, 1)) = 0) Then
        lngRetVal = lngRetVal - 1
    End If
 
    'Trim the trailing characters
    strGUID = Left$(strGUID, lngRetVal)
 
    'Remove the unwanted characters
    For lngPos = 1 To Len(strRemoveChars)
        strGUID = Replace(strGUID, Mid(strRemoveChars, lngPos, 1), "")
    Next
 
    CreateGUID = strGUID
End Function
 
Private Function GetID() As String
    Dim strGUID As String
    Dim i As Long
    Dim strHex As String
    Dim Number As Variant
    Dim strRet As String
    '
    strGUID = CreateGUID
    For i = 1 To Len(strGUID) Step 8
        strHex = "&H" & Mid(strGUID, i, 8)
        Number = Long2ULong(CLng(strHex))
        strRet = strRet & Long2ASCII33to126(Number)
    Next
    '
    GetID = strRet
End Function
 
Private Function Long2ASCII33to126(ByVal Number As Variant) As String
    Dim strRet As String
    Dim Remainder As Long
    Dim Quotient As Variant
    Dim i As Long
    '
    For i = 1 To 5
        Quotient = Int(Number / CDec(94))
        Remainder = Number - (Quotient * CDec(94))
        strRet = Chr(33 + Remainder) & strRet
        Number = Quotient
    Next
    '
    Long2ASCII33to126 = strRet
End Function
 
Private Function Long2ULong(n As Long) As Variant
    If n < 0 Then
        Long2ULong = (n And &H7FFFFFFF) + 2147483648#
    Else
        Long2ULong = n
    End If
End Function

Open in new window

0
 
aikimarkCommented:
@samic400

* Even if you use a GUID as the basis for a random string, you should use a unique index on the column where they are stored.  There is no guarantee they will be unique.  It is just highly unlikely that there will be duplicates.

* If you only need the 0-9 a-z A-Z values, you can tweak the VK-supplied routine.

===========
@VK

Clever approach to the problem.  When I write the follow-up article, I'll mention you.
0
 
VKCommented:
@aikmark
thanks for the catch
0
 
aikimarkCommented:
I've republished the VB PRNG article on EE:
http:A_11114.html
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 4
  • 3
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now