Results 1 to 5 of 5

Thread: unique random number

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Apr 2005
    Posts
    18

    unique random number

    hello,

    How can i generate unique random number in vb.I mean during the execution of application numbers ain't repeated. need code

    thanks
    Ashish

  2. #2
    Frenzied Member the182guy's Avatar
    Join Date
    Nov 2005
    Location
    Cheshire, UK
    Posts
    1,473

    Re: unique random number

    in your app do you store the generated numbers after use? You will need to store them when they are generated, so that each time it attempts to generate a number, it can check the list to see if it has already been used, if so it should generate a new one and check again etc...
    Chris

  3. #3
    PowerPoster
    Join Date
    Feb 2006
    Location
    East of NYC, USA
    Posts
    5,691

    Re: unique random number

    There should also be a check in the loop for the number of iterations. If the random number runs from 1-100, for example, after the 100th time the program will loop forever.

  4. #4
    Conquistador
    Join Date
    Dec 1999
    Location
    Australia
    Posts
    4,527

    Re: unique random number

    Randomize

    i = CInt(rnd*100000)

    Will generate a random integer between 0 and 100000, for example

    If you want it to be unique, then you'd need to store the previous ones

  5. #5
    Former Admin/Moderator MartinLiss's Avatar
    Join Date
    Sep 1999
    Location
    San Jose, CA
    Posts
    33,431

    Re: unique random number

    This will generate 9 unique numbers (in this case up to 9999)

    VB Code:
    1. Dim nTry As Integer
    2.     Dim MyCollection As New Collection
    3.    
    4.     Randomize
    5.    
    6.     Do While MyCollection.Count < 10
    7.         nTry = Int(10000 * Rnd)
    8.         ' If the number is already in the collection an error is generated
    9.         ' so it is not added
    10.         On Error Resume Next
    11.         MyCollection.Add CStr(nTry), CStr(nTry)
    12.     Loop

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