Absolute random number (no duplicates)

Source: Internet
Author: User
Tags time in milliseconds

When C # is used to generate random numbers, we generally do not want to duplicate them, but sometimes it is difficult to avoid this situation.

For exampleProgramWhen multiple random numbers are generated consecutively and the interval between them is very short, a problem occurs. The most basic way to generate a random number is:

 
  
  
1
RandomR= New Random();

However, this will not solve the problem mentioned above, and will generate many identical random numbers. Therefore, you must add a random number factor parameter at the time of generation to avoid repeated possibilities, but how should we determine this random number factor?

I have tried to use the time in milliseconds before, and I think it is okay:

  
  
1
RandomR= New Random(Unchecked((Int)(Datetime.Now.Ticks)));

This is also the practice on msdn, but even so, the computer is still running too fast, so there will be a chance to repeat, and there are still a lot of opportunities, then I try to add tick to 1 before each operation, but it still cannot be completely solved, but the probability is reduced.

However, there will always be a solution. In fact, there is a way to ensure that there are no duplicates, that is, using guid as a random factor. As we all know, GUID is absolutely impossible to be repeated, therefore, using it as a factor is the best choice,CodeAs follows:

 
  
  
1
RandomR= New Random(Guid.Newguid().Gethashcode());
Oh, this will solve the above repeated problems!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.