Problem description:In many cases, we may need to generate a large number of random numbers in a very short time, but you may find that many duplicate random numbers are generated. It is not what you want to generate a large number of different numbers, or the same number is very small.
Cause analysis:Random is a class that mainly generates pseudo-random numbers. It mainly includes two Constructor (no-argument constructor and constructor with an int32 parameter ), the parameter-free constructor mainly uses the system time as the Random Seed. The constructor with parameters needs to specify the Random Seed. When a large number of random numbers are generated in a short period of time, due to the short time, it is very likely that when a part of random numbers are generated, the system takes the same time as the Random Seed, therefore, the random numbers generated are the same.
Solution:Now that you know the cause, the solution is ready. To generate different random numbers, we only need to ensure that the random seeds are not repeated as much as possible (not completely guaranteed. The random class has two constructor functions, so we can consider using two methods to solve this problem. (If you have more and better solutions, let me know ~~)
- Using a non-argument constructor, since it uses the system time as a random seed, and the same system time is obtained, duplicate random numbers are generated, therefore, we can generate a random number and then delay it for a period of time so that it will not get the same system time next time, so that the random seeds will be different. You can use thread. Sleep (100) for latency. The latency is 0.1 seconds.
- Using the constructor with parameters, we can find a way to generate random seeds that do not repeat as much as possible. Note that when the random. nextbytes () method is introduced in msdn, the following sentence is provided: "to generate an encrypted security random number suitable for creating a random password, use a method such as rngcryptoserviceprovider. getbytes .", It contains the meaning that Microsoft already has something available to generate a random password, so we can use it. We use it to generate our random seeds.
You can write a method to generate random seeds,CodeAs follows:
1 Public Int Getrandseed ()
2 {
3 Byte [] Bytes = New Byte [ 8 ];
4 System. Security. cryptography. rngcryptoserviceprovider RNG = New System. Security. cryptography. rngcryptoserviceprovider ();
5 RNG. getbytes (bytes );
6 Return Bitconverter. toint32 (bytes, 0 );
7 }