开发者

Random number in a loop [duplicate]

This question already has answers here: Random number generator only generating one random number 开发者_C百科 (15 answers) Closed 9 years ago.

having an issue generating random numbers in a loop. Can get around it by using Thread.Sleep but after a more elegant solution.

for ...
    Random r = new Random();
    string += r.Next(4);

Will end up with 11111... 222... etc.

Suggestions?


Move the declaration of the random number generator out of the loop.

The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, ...

Source

By having the declaration in the loop you are effectively calling the constructor with the same value over and over again - hence you are getting the same numbers out.

So your code should become:

Random r = new Random();
for ...
    string += r.Next(4);


Random r = new Random(); 
for ... 
    string += r.Next(4); 

new Random() will initialize the (pseudo-)random number generator with a seed based on the current date and time. Thus, two instances of Random created at the same date and time will yield the same sequence of numbers.

You created a new random number generator in each iteration and then took the first value of that sequence. Since the random number generators were the same, the first value of their sequences was the same. My solution will create one random number generator and then return the first, the second, etc... value of the sequence (which will be different).


I found a page in Chinese that said the same with the time: http://godleon.blogspot.hk/2007/12/c.html, it said if you type like this:

Random random = new Random(Guid.NewGuid().GetHashCode());

you MAY get a random number even in a loop! It solved my question as well!


You should be using the same Random instance throughout instead of creating a new one each time.

As you have it:

for ...
    Random r = new Random();
    string += r.Next(4);

the seed value is the same for each (it defaults to the current timestamp) so the value returned is the same.

By reusing a single Random instance like so:

Random r = new Random()
for ...
    string += r.Next(4);

Each time you call r.Next(4) the values are updated (basically a different seed for each call).


Move the Random r = new Random(); outside the loop and just call next inside the loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜