C # method for generating random numbers without duplicates,

Source: Internet
Author: User

C # method for generating random numbers without duplicates,

When using the Random class to generate a Random number, we may encounter the problem of duplicate Random numbers.

For example, if we want to generate a 6-digit Verification Code, although Random is also used, it may be 111111,999999.

This is because when the Random class is instantiated, if the Random Seed is not filled in, the pseudo-Random computation is performed using the timeline as the seed by default. When the computation speed is too fast, all the Random seed is a value.

The solution is also very simple. We will not repeat it by using the Guid hash code as the seed value. The Code is as follows:

1 public class RandomHelper 2 {3 /// <summary> 4 // generate a random code (number) of the specified digits) 5 /// </summary> 6 /// <param name = "length"> </param> 7 /// <returns> </returns> 8 public static string GenerateRandomCode (int length) 9 {10 var result = new StringBuilder (); 11 for (var I = 0; I <length; I ++) 12 {13 var r = new Random (Guid. newGuid (). getHashCode (); 14 result. append (r. next (0, 10); 15} 16 return result. toString (); 17} 18}

Done.

 

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.