One question about none-repeated random numbers generation by using C# and C.

Dear all,

I wanna ask you one question about random number generation by using C and C#, and which is better according to my requirements about generating a large set of non-repeating random numbers, e.g. 10,000,000.

In order to make our topic much clear and quicker be followed up, I'd love introduce my basic understanding of random numbers definitions in C. If there are something misleading, I will be corrected and restart from the right point of view. From my current information, Random means that there is an equal chance for each of all possible numbers in the range. In other words, if one gets a 7, the next time 7 should still be one of the possiblilities, it should not be excluded. Random numbers can repeat. And it can be finished by this following statement,"rand() / (RAND_MAX / N + 1)" in the case of N is much smaller than RAND_MAX which is defined in the stdlib.h with the value 32767, meanwhile after the srand() is initilized with different seeds, e.g. system time, should be done ahead it as well. The problem is that in C, it is not possible to change the value of rand_max in stdlib.h. Therefore, only small range of random numbers are reachable. Therefore, it is not fit for my case
requirements.

In C#, there are some methods in class random in order to generate random number. E.g. a snippet code is as follows,

private int RandomNumber(int min, int max)
{
    Random random = new Random();
    return random.Next(min, max);
}
By which, the following code returns the random number between min and max. In order to make my case, I may do it 10,000,000 times.

However, the question comes again. Is there random numbers generated allowed to repeat next time, and are for my requirements Does C# modify the definition of random number, which is not the same as C, and my reqiurement about getting none-repeat random values in the set of 10,000,000 can be satisfied

Thanks in advance,

Cordially,

Luis



Answer this question

One question about none-repeated random numbers generation by using C# and C.

  • strelzj

    Int32 is -2,147,483,648 to +2,147,483,647, so you can get 10,000,000 non-repeat numbers. or you can use random.NextDouble() and mulitple by the largest value.
    but Random class doesnt remember any state infomation for performance reason. so you need to keep track of what values have been used in your application. you can keep them in memory or disk in some searchable structure eg. a HashTable, and compare to the next value you get. if the value appears you need to generate another one. that may result in more than 10,000,000 times(very likely). but if you use each generated value in your application, that shouldnt be a problem because you store them some where anyway.


  • One question about none-repeated random numbers generation by using C# and C.