Random Integer

  • Thread starter Thread starter George Durzi
  • Start date Start date
G

George Durzi

How can I choose a random integer between to given integers?

For example, I'd like to pick a random integer between 1 and 3. E.g. 1, 2,
or 3

If I do

Dim oRandom As New Random(1)
Response.Write oRandom.Next(3)

will I get a different number between 1 and 3 every time, even if I'm always
using 1 as a seed?

Thanks!
 
George said:
How can I choose a random integer between to given integers?

For example, I'd like to pick a random integer between 1 and 3. E.g. 1, 2,
or 3

If I do

Dim oRandom As New Random(1)
Response.Write oRandom.Next(3)

will I get a different number between 1 and 3 every time, even if I'm always
using 1 as a seed?

For a given seed, you'll always get the same sequence of "random"
numbers. So, yes, if you always use the seed 1, the sequence of numbers
..Next will return will be the same.

If you want a more randomized experience, simply omit the seed. The
Random class will cause a seed obtained from the system clock to be
used, so it should produce different sequences of numbers each time.

hth

--

Scott Mitchell
(e-mail address removed)
http://www.4GuysFromRolla.com

* When you think ASP.NET, think 4GuysFromRolla.com!
 
Thanks Scott, but without the seed, is there a way to ensure the number is
between, for example, 1 and 3? Or will it grab a random number between 0 and
3?
 
The seed = 1 does not mean your random number starts with 1. If you want to
get an integer between 1 - 3 just use Next(int minValue, int maxValue)

ie:
Random random = new Random();
int result = random.Next(1, 3);
 
Back
Top