Random Integer

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!
 
S

Scott Mitchell [MVP]

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!
 
G

George Durzi

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?
 
V

Victor Hadianto

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);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,234
Latest member
SkyeWeems

Latest Threads

Top