I need to generate a random integer between 1 and n (where n is a positive whole number) to use for a unit test. I don't need something overly complicated to ensure true randomness - just an old-fashioned random number.
How would I do that?
I need to generate a random integer between 1 and n (where n is a positive whole number) to use for a unit test. I don't need something overly complicated to ensure true randomness - just an old-fashioned random number.
How would I do that?
As has been pointed out many times, the suggestion to write code like this is problematic:
The reason is that the constructor for the
Random
class provides a default seed based on the system's clock. On most systems, this has limited granularity -- somewhere in the vicinity of 20 ms. So if you write the following code, you're going to get the same number a bunch of times in a row:The following code addresses this issue:
I threw together a simple program using both methods to generate 25 random integers between 1 and 100. Here's the output:
You should create a pseudo-random number generator only once:
Then, if an integer suffices for your needs, you can use:
as many times as you like. Using the wrapper function is justified only because the maximum value is exclusive - I know that the random numbers work this way but the definition of .Next is confusing.
Creating a generator every time you need a number is in my opinion wrong; the pseudo-random numbers do not work this way.
First, you get the problem with initialization which has been discussed in the other replies. If you initialize once, you do not have this problem.
Second, I am not at all certain that you get a valid sequence of random numbers; rather, you get a collection of the first number of multiple different sequences which are seeded automatically based on computer time. I am not certain that these numbers will pass the tests that confirm the randomness of the sequence.
If you are using Joseph's answer which is a great answer, and you run these back to back like this:
Then the result could come back the same over and over because it processes the call so quickly. This may not have been an issue in '08, but since the processors are much faster today, the function doesn't allow the system clock enough time to change prior to making the second call.
Since the System.Random() function is based on the system clock, we need to allow enough time for it to change prior to the next call. One way of accomplishing this is to pause the current thread for 1 millisecond. See example below:
Microsoft Example Rnd Function
https://msdn.microsoft.com/en-us/library/f7s023d2%28v=vs.90%29.aspx
1- Initialize the random-number generator.
2 - Generate random value between 1 and 6.