# Generate random number sequences that are not repeated

Source: Internet
Author: User
Tags random seed

I haven't taken any notes for a long time. I 've just been promoted to a senior member. It's really embarrassing.
In fact, we have not done anything in these days. On the contrary, we have done a lot, but we have no time to sort out what we have done and share it with you.
Now let's take this opportunity to talk about a small program compiled in the past few days.

This program is used to generate N non-repeated random numbers from 0 to n-1. Someone discussed this issue last year or at any time. Later, I compiled one for my actual needs. I feel that the efficiency is not bad. I am here to show you ugly.

First, let's introduce the basic ideas:
I wrote code in C.

1. Generation of non-repeated random numbers

When it comes to the generation of random numbers, you will surely think of the random class provided by. net. Of course, there may be other similar methods in different languages and development platforms.
The use of the random class is very simple. It provides two constructor types. One constructor has no parameters, and the other constructor has an int32 parameter as the seed for random number generation. In general use, after declaring and initializing the random object, you only need to call the next () method of the random (which has been overloaded, you can obtain a series of random numbers by setting parameters.
The number produced by random can be random, but it cannot be ensured that each number appears only once in a random number sequence, nor can it be ensured that the random number sequence is obtained after the continuous value is disrupted.
To meet the requirements just mentioned, two solutions can be adopted:

1) Create an n-dimensional array to save the generated and qualified random numbers. Use the next (n-1) method of the random class to generate a random number and compare it with the previously generated random number. If the random number has been generated, discard the current random number, re-generate a random number and compare it with the previous random number until the generated random number has not appeared before. Add this random number to the array. In the same way, n random numbers that meet the conditions are generated.

2) create an n-dimensional array to save the generated random number. Create an n-dimensional bool array flag and initialize all elements to false, indicates whether a random number has been generated. Similarly, the next (n-1) method of the random class is used to generate the random number TMP and determine whether the flag [TMP] is true. If it is true (it indicates that TMP has been generated before ), discard TMP and re-generate the random number to TMP. Continue to judge until flag [TMP] is false (it indicates that TMP has not appeared before ), in this case, the flag [TMP] is assigned true, indicating that TMP has been generated. In the same way, n random numbers that meet the conditions are generated.
The two solutions are obviously better than the former. Although the latter declares an array of the bool type, loop nesting is avoided, which greatly reduces the time complexity and effectively improves the running efficiency of the program.

2. display of random numbers

Comparison between the string class and the stringbuilder class
Since we use a window to implement this program, we need to convert each element in the newly generated random number array into a string and add it to an existing random number string during the display process.
At the beginning, use a string type and use the "+" or insert () operator. However, the efficiency of this method is extremely low, and it is even slower than the generation of random numbers.
Later, the stringbuilder string was used for operations, and the append () method was used for string combination. The efficiency is significantly improved.
The efficiency of string and stringbuilder in string combination varies mainly because string is static, while stringbuilder is dynamic.
Adding a string to a string is equivalent to assigning a new string to a variable, and the string is discarded; however, to add a string to a stringbuilder string is to add the string to the original string without creating a new object. This is the advantage of dynamic string processing.

3. Process Timing Method

In the second question just now, I gave the efficiency of using the string and stringbuilder types through the program execution time. The time here is not my subjective feeling, but obtained by using the datetime class timing in the program. The specific method is to write the "datetime start = datetime. now; ", after the program segment ends, write" string timecost = (datetime. now-Start ). tostring ();". In this way, the time consumed by the program segment is saved in the timecost string.

4. textbox input verification: validating

I also tried the validating event while changing the program.
Let's refer to the following link in msdn:
When you use the keyboard (tab, Shift + TAB, etc.), call the select or selectnextcontrol method, or call containercontrol .. ::. when the focus is changed by setting the activecontrol attribute to the current form, the focus event occurs in the following order:
Enter
Gotfocus
Leave
Validating
Validated
Lostfocus
When you change the focus by using the mouse or calling the focus method, the focus event occurs in the following order:
Enter
Gotfocus
Lostfocus
Leave
Validating
Validated
If the causesvalidation attribute is set to false, the validating and validated events are canceled.
This statement tells us when validating and other similar events will occur. In the program, this event is used to determine whether the input content in the textbox that inputs the random number seed and the number of random numbers is legal. If the value is invalid, go to the input Textbox Control again.

Code:
1. Private void textbox_validating (Object sender, system. componentmodel. canceleventargs E)
2. {
3. Try
4. {
5. Convert. toint32 (sender as textbox). Text );
6. }
7. Catch (exception)
8. {
9. MessageBox. Show ("enter a value! ");
10. (Sender as textbox). selectall ();
11. (Sender as textbox). Focus ();
12. }
13. }

I do not know whether this verification method is reasonable. Please kindly advise.

The following is the test result of the program running:
My computer CPU: p8700 (2.53g dual-core); Memory: 2G; System: win7

// Generate a random number using a double loop nested array and display it with stringbuilder
Quantity: 90000
Seed: 234
Time consumed: 00: 03: 38.8595180
Time consumed: 00: 00: 06.2623582

// Generate a random number using two arrays and display it using stringbuilder
Quantity: 90000
Seed: 234
Time consumed for obtaining: 00: 00: 06.3733645
Time consumed: 00: 00: 06.3743646

// Use two arrays to generate random numbers and display them with strings
Quantity: 90000
Seed: 234
Time consumed for obtaining: 00: 00: 06.5443743
Display time: 00: 02: 47.9316051

It's not a long time. Let's show you the code.

Code:
1. // Use an array to generate a random number
2. /* Initialization
3. * Note:
4. * Table Initialization is not required here,
5. * In comparison with TMP, only the data updated by valid random numbers is compared.
6. */
7. Num = convert. toint32 (textbox3.text); // textbox3 is used to enter the total number of random numbers.
8. Table = new int [num];
9. Textbox1.text = "";
10. Textbox1.update ();
11. Progressbar1.maximum = num;
12. // Generate a random number
13. /*
14. * (1) the last number is calculated instead of the random number.
15. * This method saves about 1 s when num = 10000
16. */
17. Random Rand = new random (convert. toint32 (textbox2.text); // textbox2 is used to input Random Seed
18. Datetime time1 = datetime. Now; // used to obtain the timing of a random number
19. Int sum1 = 0, sum2 = 0; // (1) Two parameters used to calculate the last number
20. For (int K = 0; k <num-1; k ++) // (1) here only loop num-1 times
21. {
22. Bool flag; // used to determine whether the current random number has been generated before: Yes)
23. Int TMP;
24. Do
25. {
26. Flag = false;
27. TMP = Rand. Next (Num );
28. For (Int J = 0; j <K; j ++)
29. {
30. If (TMP = table [J])
31. {
32. Flag = true;
33. Break;
34. }
35. }
36. } While (FLAG); // If yes, a new random number is generated again.
37. Table [k] = TMP; // if no such random number is generated, save the random number and start searching for the next random number.
38. Sum1 + = k + 1; // (1) Calculate the parameter used by the last number, and record the sum from 1 to num
39. Sum2 + = table [k]; // (1) Calculate the parameters used for the last number, record the sum of the preceding num-1 random numbers
40. Progressbar1.value = K;
41. This. Text = "random number generated:" + K. tostring ();
42. }
43. Table [num-1] = sum1-sum2; // (1) calculates the last value.
44. Textbox1.text + = ("Quantity:" + num. tostring () +
45. "/R/n seed:" + textbox2.text +
46. "/R/N:" + (datetime. Now-time1). tostring () + "/R/N ");
47. Textbox1.update ();
48. // Display random number
49. Progressbar1.value = 0;
50. // String tmpstr = ""; // use the string type to display random numbers
51. Stringbuilder tmpstrb = new stringbuilder (""); // use the stringbuilder type to display random numbers
52. Datetime time2 = datetime. Now; // used to display the timing of a random number
53. For (INT I = 0; I <num; I ++)
54. {
55. // Tmpstr + = (I. tostring ("000000") + "|" + Table [I]. tostring () + "/R/N"); // use the string type to display random numbers
56. Tmpstrb. append (I. tostring ("000000") + "|" + Table [I]. tostring () + "/R/N"); // use the stringbuilder type to display random numbers
57. Progressbar1.value = I;
58. This. Text = "display random number:" + I. tostring ();
59. }
60. Textbox1.text + = "display time:" + (datetime. Now-time2). tostring () +
61. "/R/n *************/R/n sequence number | value/R/N ";
62. // Textbox1.text + = tmpstr; // use the string type to display random numbers
63. Textbox1.text + = tmpstrb; // use the stringbuilder type to display random numbers
Code:
1. // Use two arrays to generate random numbers
2. // Initialization
3. Num = convert. toint32 (textbox3.text );
4. Table = new int [num];
5. Test = new bool [num]; // used to determine whether the current random number has been generated before. Generated (true)
6. Textbox1.text = "";
7. Textbox1.update ();
8. Progressbar1.maximum = num;
9. For (INT I = 0; I <num; I ++)
10. {// Clear the random number sequence. That is, each element in the sequence is assigned a value beyond the range of the required random number.
11. Test [I] = false;
12. }
13.
14. // Generate a random number
15. /*
16. * (1) the last number is calculated instead of the random number.
17. * This method saves about 1 s when num = 10000
18. */
19. Random Rand = new random (convert. toint32 (textbox2.text ));
20. Int sum1 = 0, sum2 = 0; // (1) Two parameters used to calculate the last number
21. Datetime time1 = datetime. Now; // used to obtain the timing of a random number
22. For (int K = 0; k <num-1; k ++) // (1) here only loop num-1 times
23. {
24. Int TMP;
25. Do
26. {
27. TMP = Rand. Next (Num );
28. } While (test [TMP]); // If yes, a new random number is re-generated.
29. Test [TMP] = true;
30. Table [k] = TMP; // if no such random number is generated, save the random number and start searching for the next random number.
31. Sum1 + = k + 1; // (1) Calculate the parameter used by the last number, and record the sum from 1 to num
32. Sum2 + = table [k]; // (1) Calculate the parameters used for the last number, record the sum of the preceding num-1 random numbers
33. Progressbar1.value = K;
34. This. Text = "random number generated:" + K. tostring ();
35. }
36. Table [num-1] = sum1-sum2; // (1) calculates the last value.
37. Textbox1.text + = ("Quantity:" + num. tostring () +
38. "/R/n seed:" + textbox2.text +
39. "/R/N:" + (datetime. Now-time1). tostring () + "/R/N ");
40. Textbox1.update ();

End !!!

Related Keywords:

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.