Results 1 to 3 of 3

Thread: problem in generating distinct random numbers

  1. #1

    Thread Starter
    Registered User
    Join Date
    Oct 2001
    Location
    mysore
    Posts
    60

    problem in generating distinct random numbers

    i am using this below code to generate random numbers
    g=cint(rnd*10)+1
    msgbox g
    but some time repeating random numbers occurs like when i click
    command button msgbox giving 6 and when i click command button IInd time msgbox giving 4 and for IIIrd time it is once again
    giving 6 this is what i want to prevent, how can i prevent this.

  2. #2
    Retired VBF Adm1nistrator plenderj's Avatar
    Join Date
    Jan 2001
    Location
    Dublin, Ireland
    Posts
    10,359
    Well just store the numbers in an array, then check through the array if the number is there or not.
    Are you calling Randomize before you start calling Rnd() ?
    Microsoft MVP : Visual Developer - Visual Basic [2004-2005]

  3. #3
    Retired VBF Adm1nistrator plenderj's Avatar
    Join Date
    Jan 2001
    Location
    Dublin, Ireland
    Posts
    10,359
    Here's a way of doing it.

    VB Code:
    1. Private Sub Form_Load()
    2.     Dim myArray(0 To 99) As Boolean
    3.     Dim i As Long, n As Long
    4.     Randomize
    5.     For i = 0 To 9
    6.         n = CLng(100 * Rnd)
    7.         If Not myArray(n) Then
    8.             myArray(n) = True
    9.         End If
    10.     Next
    11.     For i = 0 To 99
    12.         If myArray(i) Then Debug.Print "'Unique' Random Number : " & i
    13.     Next
    14. End Sub

    It'll also sort the numbers for you
    Microsoft MVP : Visual Developer - Visual Basic [2004-2005]

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