Record the random probability and performance improvement of a random string Generation Algorithm

Source: Internet
Author: User
Tags arabic numbers repetition

Record the random probability and performance improvement of a random string Generation Algorithm
I. Preface background a few days ago, a project of my department connected to a bank experienced repeated business IDs, leading to many unforeseen bugs. Because the project has a capital flow and involves money transactions, it is not afraid of any loss. So leader sent the Handler. ashx. cs written by his colleagues to me. The code generated by a serial number caught my attention. The Code is as follows: string [] str1 = new string [] {"A", "B", "C", "D", "E", "F ", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P ", "Q", "R", "S", "T", "U", "V", "W", "X", "Y ", "Z"}; string [] str2 = new string [] {"a", "B", "c", "d", "e", "f ", "g", "h", "I", "j", "k", "l", "m", "n", "o", "p ", "q", "r", "s", "t", "u", "v", "w", "x", "y ", "z"}; string [] str3 = new string [] {"0", "1", "2", "3", "4", "5 ", "6", "7 ", "8", "9"}; Random r = new Random (); int s1 = r. next (0, str1.Length-1); string a1 = str1 [s1]; r = new Random (); int s2 = r. next (0, str2.Length-1); string a2 = str2 [s2]; r = new Random (); int s3 = r. next (0, str3.Length-1); string a3 = str3 [s3]; string lsh = a1 + a2 + a3; because the transaction may fail halfway, the order number remains unchanged, but the sequential number is generated again. That is to say, at the beginning of the transaction, a fixed order number is generated. By the end of the final transaction, this business process may be successful once, and may be repeated multiple times to succeed. After all, the transaction may fail for the first time, it may also fail several times in a row. Business Id = Transaction Order Number + sequential number, where the order number is reserved for 9 digits. Sequential number is a three-character random string consisting of uppercase and lowercase English letters and numbers. Because the order number is fixed and unique, as long as the generated serial number is unique, the Business Id can be unique. However, the uniqueness of the sequential number depends on the order number. Similar to grouping by the order number, the sequential number in each group cannot be repeated. So I hurriedly asked my colleagues who maintained the project, according to the previous practice, how many times a transaction could fail at most to succeed, and my colleagues said it would not exceed 10-12 times. That is to say, a single order number can generate up to 12 sequential numbers, and a maximum of 238328 types of three random strings consisting of uppercase and lowercase English letters and Arabic numbers. However, I can see from my colleague's code that the random string generated by my colleague is composed of [uppercase English letters + lowercase English letters + Arabic numerals], and according to this fixed combination method, A maximum of 26*26*10 = 6760 types of three random strings can be generated. Obviously, the repetition probability is too high. Then, let's take a look at the above Code. We can see that my colleague uses the default seed value related to time to initialize a new instance of the Random class. Three Random objects are instantiated. Obviously, three Random objects may generate identical Random numbers. By default, the nonparametric constructor of the Random class uses the system clock to generate its seed value, while the parameterized constructor can use the Int32 value based on the number of time cycles of the current time. However, because the clock resolution is limited, if you use a non-parameter constructor to continuously create different Random objects, a Random number generator will be created to generate the same Random number sequence. After such analysis, it is clear that this method of generating three random strings has a great risk of repetition. As bloggers have always advocated that the primary goal of working in the company is to quickly solve the problem, the bloggers decided to go online and find out if there is any common and reliable code. But it was almost twists and turns and found that most of them were unsatisfactory. Okay, just pull up your sleeves and create your own wheels! Ii. Technical Implementation 1. the Random class is a pseudo-Random number generator. a pseudo-Random number is selected from a finite number with the same probability. The numbers selected are not completely random, because they are selected using a definite mathematical algorithm, but from a practical point of view, their degree of randomness is sufficient. However, when used in the above scenarios, the user always finds that the randomness is weak, so the blogger made a new discovery on MSDN and found a class that can generate strong random numbers: RNGCryptoServiceProvider. This class can be implemented using the implementation provided by the encryption service provider (CSP) to encrypt the Random number generator (RNG). Obviously, the randomness is greater than that of the Random class. Private int GetRandomInt (int maxValue) {if (maxValue <0) {throw new ArgumentOutOfRangeException ("maxValue", "maxValue is less than zero. ");} S_rng.GetBytes (S_buffer); int value = BitConverter. toInt32 (S_buffer, 0); value = value % (maxValue + 1); if (value <0) value =-value; return value ;} 2. Since my colleagues fixed the method of generating random strings to [uppercase letters + lowercase English letters + Arabic numerals], this is obviously not the case, you can also use [uppercase English letters + uppercase English letters], [uppercase English letters + Arabic numbers + uppercase English letters], and other combinations. That is, the combination in mathematics. m elements are randomly extracted from n different elements for combination, allowing repeated elements in the combination, for example, four random strings are generated: [uppercase English letters + lowercase English letters + Arabic numerals]. To enable repeated combinations of multiple data types, the generic type is used. Private void GetAllCombination <T> (List <T []> values, T [] array, T [] buffer, int index) {if (index = 0) {foreach (T value in array) {buffer [0] = value; T [] tmp = new T [buffer. length]; buffer. copyTo (tmp, 0); int l = tmp. length; for (int I = 0; I <l/2; I ++) {T t = tmp [I]; tmp [I] = tmp [l-I-1]; tmp [l-I-1] = t;} values. add (tmp) ;}} else {foreach (T value in array) {buffer [index] = valu E; GetAllCombination (values, array, buffer, index-1) ;}} private List <T []> GetAllCombination <T> (T [] array, int m) {List <T []> values = new List <T []> (); T [] buffer = new T [m]; GetAllCombination (values, array, buffer, m-1); return values;} 3. To ensure that the random strings generated by the same instance object of the RandomString class are unique, the blogger deliberately creates a container internally, and lock to support multi-thread access. /// <Summary> /// generate a random string consisting of uppercase and lowercase letters and numbers /// </summary> /// <returns> </returns> public string next () {while (true) {string indexType = CombinationType [GetRandomInt (CombinationType. count-1)]. item2; string randomString = string. empty; foreach (var item in indexType) {randomString + = GetRandomChar (item. toString ();} lock (this. _ lockObj) {if (! This. _ listRandomString. contains (randomString) {this. _ listRandomString. add (randomString); return randomString ;}}}} 4. extended attributes /// <summary> /// location combination of random strings /// </summary> public List <Tuple <int, string, int >>> CombinationType {get; private set ;} /// <summary> /// random string that can be generated by the RandomString object instance at most /// </summary> public int Count {get; private set ;} iii. Conclusion: The above key codes are all posted. The bloggers only elaborate on their own ways of thinking. With the help of this article, I hope you can give some advice. The combination of recursive algorithms will inevitably lead to poor performance. Is there any other way to optimize it? Performance tests show that a bottleneck occurs when m is 13.

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.