tags:

views:

122

answers:

4

i use

Random rnd = new Random();
x=rnd.Next(10);

but every time i get the same number. how to fix it and get different numbers? Tell me easy method.

thanks. sorry for bad english.

+10  A: 

Random's default constructor uses the current time as its seed. Therefore, if you initialize multiple Random objects in rapid succession (such as in a loop, for instance), they will share the same seed.

Create your Random object once and use it multiple time, or create a seed beforehand and use it to initialize your generators.

Etienne de Martel
In the vast majority of cases creating a static `Random` instance and then using it as long as the program lives, is the proper way to go. If you need more then you likely (hopefully) know enough about PRNGs anyway to avoid the common mistakes.
Joey
Create a single Random object and then use it multiple times instead of creating a new one each time.Also, System.Random should **NOT** be used for anything security related. For that you should use RNGCryptoServiceProvider (http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider.aspx)
Eadwacer
A: 

Obligatory XKCD reference:

http://xkcd.com/221/

ceejayoz
*sigh* ... Even if it still were funny the twentieth time you have to see this crop up in connection to (pseudo-)random numbers ... it's not an answer to the question, nor particularly helpful.
Joey
also, http://www.dilbert.com/dyn/str_strip/000000000/00000000/0000000/000000/00000/2000/300/2318/2318.strip.gif is much more relevant
balpha
That's the other one that appears frequently, albeit slightly less so. Still, both are unlikely to help anyone and serve only to entertain a select few.
Joey
Yeahh...it's getting pretty old. Let it die.
Mark
@Johannes I agree with you for the most part, although the Dilbert one actually has some sense to it (while the XKCD one isn't much more than a joke). Either way, neither of them is an answer to the question.
balpha
A: 

Make sure you use the constructor only once. You can add a seed.

Random rnd  = new Random(DateTime.Now.Millisecond);

Then you can make calls to as you actually did it.

x=rnd.Next(10);

But make sure you don't have the constructor and the call to the Next() method inside a loop or something similar...

Jonathan
That's quite a poor seed. You only get 1000 different sequences out of it, one of which starts with 0 (which is a *very* poor seed for most PRNGs [excluding the WELL generators, but even then]). The default for `Random` is the current number of ticks which is much better than this but still you can get the same sequence if you happen to create new instances too fast. The real problem is likely that they create a new `Random` instance over and over again in a loop.
Joey
+2  A: 

MSDN explicitly addresses this "problem" in the remarks section of the MSDN docs for the Random class, including a sample!

http://msdn.microsoft.com/en-us/library/system.random.aspx

Lucero