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?
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With