Web undim.blogspot.com
 Visual Basic developer's world
Friday, March 23, 2007
Easily generating random numbers
From John Slaughter

If you use random numbers to a large extent, you probably get tired of always having to put in Randomize and then the equation. This simple subroutine handles both chores for you. First, put the following routine in your project's main module.

Public Function GenRndNumber(Upper As Integer, Lower As Integer) As Integer
Randomize
GenRndNumber = Int((Upper - Lower + 1) * Rnd + Lower)
End Function

To get a random number between 99 and -99, just enter:

RandomNumber = GenRndNumber(99, -99)

You can get a random letter between "A" and "M" with this:

RandomLetter = Chr\$(GenRndNumber(asc("M"), asc("A")))

You can eliminate the middle of a range by putting the call to GenRndNumber inside a DO Loop. The following will get a random number from 50 to 99 or -50 to -99.

'Initialize the number to be generated within the area you want excluded.
RandomNumber = 0
Do Until Abs(RandomNumber) > 49
RandomNumber = GenRndNumber (99, -99)
Loop

Be sure to declare RandomNumber and RandomLetter as appropriate. This procedure has a minor benefit for anyone who uses a lot of calls to the random number generator. It actually generates slightly less machine code than calls to the RND function. While not generally a concern nowadays, there may be times when a programmer will need to find a way to cut down on the amount of generated machine code.

Labels: , , ,

 About Me Name: Admin Home: The NeverLands About Me: A source code wonderer since the early 80s with my first ZX81 by Sinclair, home computer. See my complete profile Previous Post Archives Must-See Places ΣΚΛΗΡΥΝΣΗ ΚΑΤΑ ΠΛΑΚΑΣ - ΕΓΚΕΦΑΛΟΣ - ΕΓΚΕΦΑΛΟΓΡΑΦΗΜΑ - ΑΝΟΙΑ - ΝΕΥΡΟΛΟΓΟΣ - ΨΥΧΙΑΤΡΟΣ - ΛΟΙΜΩΔΗΣ ΜΟΝΟΠΥΡΗΝΩΣΗ - ΠΑΡΚΙΝΣΟΝ - ΑΓΧΟΣ - ΚΑΤΑΘΛΙΨΗ - ALZHEIMER - EPSTEIN BARR eurolife Template By