Re: non repeating random numbers
From: Rick Rothstein (rickNOSPAMnews_at_NOSPAMcomcast.net)
Date: 05/18/04
- Next message: Peri: "How to change the font for a VB Form (Me.Font = "MURASU5-System" --> Not an English Font) in run time?"
- Previous message: mayayana: "Re: DOM - WebBrowse - Get CLASS of TD (or other) elements?"
- In reply to: allan go: "non repeating random numbers"
- Next in thread: allan go: "Re: non repeating random numbers"
- Reply: allan go: "Re: non repeating random numbers"
- Messages sorted by: [ date ] [ thread ]
Date: Tue, 18 May 2004 08:55:24 -0400
> Ey! Can anyone explain to me how pickedrandom(j) = 0 allows the pc to
> continually pick a random number that is non repeating?
>
> Randomize
> For i = 1 To 10
> j = Int(Rnd * 10) + 1
>
> Do Until pickedrandom(j) = 0
> j = Int(Rnd * 10) + 1
> Loop
>
> pickedrandom(j) = i
> numbersfinal(i) = j
> Next
First off, I'd say this is an inefficient looping structure. What it is
doing is looking for elements of the pickedrandon array that have not
had a number assigned to them... that's what the pickedrandom(j)=0 is
doing... one at a time and, once found, assigns random numbers to them.
The first time you Dim (or in the case of dynamic arrays, ReDim) a
numeric array, all of its elements are set to zero. Since the numbers
being assigned are from 1 to 10 (hence, non-zero), you can test the
element to see if it equals zero... if it does, it means no random
number greater than zero (from 1 to 10) has yet been assigned to it.
This is what the test in the Do Until statement is doing.
However, as I said in the beginning, this method of assigning
non-repeating random numbers is inefficient... the loop can cycle around
quite a number of times looking for elements that are equal to zero,
especially as more and more elements become filled so that it becomes
hard to find a zero-element to fill. A more efficient method is to use
the RandomizeArray subroutine contained in the example code at this
link.
http://vbnet.mvps.org/code/helpers/randomarray.htm
The method used there is to assign number in consecutive order to an
array and then use the RandomizeArray subroutine to swap them around. It
does this by only going through the array one time with no repeats
(making it an efficient method to use).
Rick - MVP
- Next message: Peri: "How to change the font for a VB Form (Me.Font = "MURASU5-System" --> Not an English Font) in run time?"
- Previous message: mayayana: "Re: DOM - WebBrowse - Get CLASS of TD (or other) elements?"
- In reply to: allan go: "non repeating random numbers"
- Next in thread: allan go: "Re: non repeating random numbers"
- Reply: allan go: "Re: non repeating random numbers"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|