
Generating a series of unique random numbers
What is the best way to generate a series of 20 unique random numbers using vbScript?

Generate a single..
.. random number and put that in a loop. Save each random number to a string or array.<BR>

Not enough...
You then have to loop through the elements *already* in the array to be sure you don't duplicate the number.<BR><BR>If you need numbers from (say) 1 to 20 "shuffled" randomly, then see the ASPFAQs for my shuffling algorithm.<BR><BR>And if want to see how I picked N random numbers from a much larger range, look at the ASPFAQs to see how I picked random records.<BR><BR>However...<BR><BR>As cutesy as the random records code is (it uses strings and INSTR to detect duplicates), it turns out that for only 20 numbers you are better off just using the array and looping through it.<BR><BR><%<BR>Randomize<BR><BR>' get 20 numbers, each in range 1 to 100<BR>Dim nums(19)<BR><BR>cnt = 0<BR>While cnt < UBound(nums)<BR> r = 1 + Int( 100 * Rnd )<BR> match = False<BR> For i = 0 To cnt1<BR> If nums(i) = r Then <BR> match = True<BR> Exit For<BR> End If<BR> Next<BR> If Not match Then <BR> nums(cnt) = r<BR> cnt = cnt + 1<BR> End If<BR>Loop<BR>%><BR><BR>Probably can be done more efficiently. That's just off the top of my head.<BR><BR>

I would have done...
Dim nums<BR>Dim cnt<BR><BR>cnt = 0<BR>While cnt < 19<BR> r = 1 + Int( 100 * Rnd )<BR><BR> If InStr(nums, "," & r & ",") = 0 Then<BR> cnt = cnt + 1<BR> nums = nums & "," & r & ","<BR> End If<BR>Wend<BR><BR>nums = Mid(nums, 2, Len(nums)  2)<BR>nums = Split(Replace(nums, ",,", ","), ",")<BR><BR>Don't know if it's better or worse, just a different way.

RE: Not enough...
Thanks very much. The loop within the loop was what I was looking for.

That's what I did...
...here: http://www.aspfaqs.com/aspfaqs/ShowFAQ.asp?FAQID=65<BR><BR>But then there was a long thread on another forum (I think on AspIn.com?) where we talked about the performance of this kind of stuff. Turned out that the overhead of building the strings up is worse than the overhead of the array loop, at least for picking up to around 100 numbers. Certainly faster with the array for only 20 numbers.<BR><BR>If it's any comfort, that answer sure surprised me.<BR><BR>I guess I should note that we are talking a difference of less than a millisecond for 100 numbers. So it's not a huge deal, obviously.<BR><BR><BR>
Posting Permissions
 You may not post new threads
 You may not post replies
 You may not post attachments
 You may not edit your posts

Forum Rules

