C # usage of Random Functions

Source: Internet
Author: User
Tags random seed

Copy codeThe Code is as follows: private static char [] constant =
{
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9 ',
'A', 'B', 'C', 'D', 'E', 'E', 'F', 'G', 'h', 'I', 'J ', 'k', 'l', 'M', 'n', 'O', 'P', 'Q', 'R', 's','t ', 'U', 'V', 'w', 'x', 'y', 'z ',
'A', 'B', 'C', 'D', 'E', 'E', 'F', 'G', 'h', 'I', 'J ', 'k', 'l', 'M', 'n', 'O', 'P', 'Q', 'R', 's','t ', 'U', 'V', 'w', 'x', 'y', 'Z'
};
Public static string GenerateRandomNumber (int Length)
{
System. Text. StringBuilder newRandom = new System. Text. StringBuilder (62 );
Random rd = new Random ();
For (int I = 0; I <Length; I ++)
{
NewRandom. Append (constant [rd. Next (62)]);
}
Return newRandom. ToString ();
}

Random numbers are widely used. They can be used to randomly display images. They can be used to prevent bored people from bumping in the Forum and encrypt information. This article discusses how to randomly generate several random numbers in a given number range. For example, randomly generate 6 random integers from 1 to 20, this article introduces the usage of random numbers in Visual c.

. Net. Frameword provides a special Random generation class System. Random, which is imported by default and can be used directly during programming. We know that a computer cannot generate completely random numbers. The numbers it generates are called pseudo-random numbers. They are selected from a group of finite numbers with the same probability, the selected number is not random, but its degree of randomness is sufficient.
We can use the following two methods to initialize a random number generator;
The function is used in this way, such as a random number between 100 and 999.Copy codeThe Code is as follows: Random ran = new Random ();
Int RandKey = ran. Next (100,999 );

However, there will be duplicates. You can give the Random a system time as a parameter to generate a Random number and it will not be repeated.
The first method does not specify a random seed. The system automatically selects a Random Seed before the current time:
Copy codeThe Code is as follows: Random ra = new Random ();

The second method is to specify an int type parameter as a random seed:
Copy codeThe Code is as follows: int iSeed = 6;
Random ra = new Random (iSeed );

Next we will use the Random. Next () method to generate a Random number.Copy codeThe Code is as follows: ra. Next ();

It returns a number greater than or equal to zero and less than 2,147,483,647, which does not meet our needs. Next we will introduce its overloaded functions and other methods.Copy codeThe Code is as follows: publicvirtualint Next (int); usage: ra. next (20)

Returns a positive random number that is less than the specified maximum value (20 here.Copy codeThe Code is as follows: publicvirtualint Next (int minValue, int maxValue );

Usage: ra. next (1, 20)
Returns a random number in the specified range (between 1 and 20). This function is used in the following instances.
There are several methods for the System. Random class:
Public method:
NextBytes uses a random number to fill in the elements of the specified byte array.
NextDouble returns a random number between 0.0 and 1.0.
Protected methods:
Sample returns a random number between 0.0 and 1.0, which can only be accessed by subclass objects.
The above describes the basic usage of random numbers. Next we will use an instance for further introduction. You must randomly generate several random numbers in a given number range. For example, you can randomly generate six random integers from 1 to 20.
The following two functions are used: getRandomNum and getNum:Copy codeThe Code is as follows: publicint [] getRandomNum (int num, int minValue, int maxValue)
{
Random ra = new Random (unchecked (int) DateTime. Now. Ticks ));
Int [] arrNum = newint [num];
Int tmp = 0;
For (int I = 0; I <= num-1; I ){
Tmp = ra. Next (minValue, maxValue); // random count
ArrNum [I] = getNum (arrNum, tmp, minValue, maxValue, ra); // The retrieved value is assigned to the array.
}
Return arrNum;
}

GetRandomNum is the random number of num in the interval [minValue, maxValue]. The returned array contains the result.
The Random number is the Random ra = new Random (unchecked (int) DateTime. now. ticks); why not use Random ra = new Random (); (the system automatically selects a Random Seed before the current time?

It is not safe to use system time as random seed. If an application runs on a fast computer, the system clock of the computer may not have time to change between calls of this constructor, the seed values of different Random instances may be the same. In this case, we need another algorithm to ensure the randomness of the generated numbers. Therefore, to ensure that the random number is "random", we have to use a more complex method to obtain random seeds. In the above program, we first use the system time as the random seed, and then multiply the random number generated last time with the cyclic variable and an integer Parameter Related to the system time, as a Random Seed, different random seed is obtained each time, and a random number is generated.

The getNum function is recursive. It is used to check whether the generated random number is repeated. If the obtained number and the obtained number are repeated, the random number is obtained again. It is worth noting that a random number instance must be used for generation. Therefore, ra must be passed in to getNum as a parameter. Otherwise, the generated number will be repeated.Copy codeThe Code is as follows: publicint getNum (int [] arrNum, int tmp, int minValue, int maxValue, Random ra ){
Int n = 0;
While (n <= arrNum. Length-1)
{
If (arrNum [n] = tmp) // use loops to determine whether there are duplicates.
{
Tmp = ra. Next (minValue, maxValue); // obtain the result randomly.
GetNum (arrNum, tmp, minValue, maxValue, ra); // recursion: If the obtained number is repeated with the obtained number, it is randomly retrieved.
}

}
Return tmp;
}

The last step is to display the data. The number displayed when a button is clicked is displayed in a label.Copy codeThe Code is as follows: privatevoid button#click (object sender, System. EventArgs e)
{
Int [] arr = getRandomNum (6, 1, 20); // obtain 6 random numbers from 1 to 20.
Int I = 0;
String temp = "";
While (I <= arr. Length-1 ){
Temp = arr [I]. ToString ()"";
I;
}
Label1.Text = temp; // displayed in label1
}

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.