Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random number in a loop [duplicate]

Tags:

c#

random

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?

like image 763
Sam Avatar asked Jun 16 '10 13:06

Sam


People also ask

How do you generate a random number in a for loop?

To get the number we need the rand() method. To get the number in range 0 to max, we are using modulus operator to get the remainder. For the seed value we are providing the time(0) function result into the srand() function.

Do random number generators repeat?

The numbers generated are not truly random; typically, they form a sequence that repeats periodically, with a period so large that you can ignore it for ordinary purposes. The random number generator works by remembering a seed value which it uses to compute the next random number and also to compute a new seed.

How can I generate multiple random numbers in C++?

rand() rand() function is an inbuilt function in C++ STL, which is defined in header file <cstdlib>. rand() is used to generate a series of random numbers. The random number is generated by using an algorithm that gives a series of non-related numbers whenever this function is called.


1 Answers

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);
like image 135
ChrisF Avatar answered Oct 13 '22 22:10

ChrisF