Link to home
Start Free TrialLog in
Avatar of Rorc
RorcFlag for United States of America

asked on

Generate Random Number Within a predetermined range - VB.NET

I am trying to generate a random number in a VB .Net application but I need the number to be within a predetermined range (the range will be 0 to TotalCount).

I know this can be done, but it's been forever since I've done it and I nolonger have MSDN information files available.

If anyone has any ideas, let me know.

Thanks,

Rorc
ASKER CERTIFIED SOLUTION
Avatar of inq123
inq123

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Rorc

ASKER

Thank you, I knew it could be done but just couldn't remember how.
Avatar of Mike Tomlinson
Just remember that the value passed into the Next method is NOT included.  In the example below, a number between 0 and 14 inclusive will be returned:

        Dim TotalCount As Integer = 15
        Dim RandomClass As New Random
        Dim RandomNumber As Integer
        RandomNumber = RandomClass.Next(TotalCount)

Here is the Random.Next() help:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemrandomclassnexttopic3.asp

From the Return value remarks:
"A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not MaxValue. If minValue equals maxValue, minValue is returned."

This also holds true for the Next() method that acceps two parameters.  The first value will be included but the second will not:

        Dim RandomClass As New Random
        Dim RandomNumber As Integer
        RandomNumber = RandomClass.Next(4, 15)

The above will return a value between 4 and 14 inclusive.

~IM