The use of c random functions

  • 2020-05-17 06:09:21
  • OfStack


private static char[] constant =   
      {   
        '0','1','2','3','4','5','6','7','8','9',  
        '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',   
        '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'   
      };
        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();
        }

The use of random Numbers is very common, it can be used to randomly display pictures, to prevent boring people in the forum water can also be used to encrypt messages and so on. This article discusses how to randomly generate several different random Numbers in a 1-digit interval, such as 6 different integers from 1 to 20, and introduces the use of random Numbers in Visual c#.

A class called System.Random is provided in.net.Frameword to generate random Numbers. This class is imported by default and can be used directly during programming. As we know, a computer cannot produce completely random Numbers. The Numbers it generates are called pseudo-random Numbers, which are selected from a finite set of Numbers with the same probability. The selected Numbers are not completely random, but in practical terms, they are random enough.
We can initialize a random number generator in the following two ways.
The function is used like this, for example, a random number between 100 and 999

Random ran=new Random();
int RandKey=ran.Next(100,999);

However, there will be a repetition. You can give Random1 system time as a parameter to generate random Numbers, so there will be no repetition
The first method does not specify the random seed, and the system automatically selects the random seed before the current time:

Random ra=new Random();

The second method is to specify one int type parameter as a random seed:

int iSeed=6;
Random ra=new Random(iSeed);

Next we use the Random.Next () method to generate random Numbers.

ra.Next();

It returns a number greater than or equal to zero and less than 2,147,483,647. This does not satisfy our needs.

publicvirtualint Next(int); Usage: ra.next(20)

Returns a positive random number that is less than the specified maximum value (20 here).

publicvirtualint Next(int minValue, int maxValue);

Usage: ra. next (1, 20)
Returns a random number within a specified range (in this case, between 1 and 20), which we will use in the following example.
Class System.Random has several other methods:
Public methods:
NextBytes populates the element of the specified byte array with a random number.
NextDouble returns a random number between 0.0 and 1.0.
Protected method:
Sample returns a random number between 0.0 and 1.0, allowing only subclass objects to access it.
The basic use of random Numbers has been described above. Let's take it a step further with an example. To randomly generate a number of different random Numbers within a 1-digit interval, for example, randomly generate 6 different integers between 1 and 20.
The main functions are getRandomNum and getNum:

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 access 
arrNum[i]=getNum(arrNum,tmp,minValue,maxValue,ra); // Extract the value and assign it to the array 
}
return arrNum;
}

getRandomNum is to extract the different random Numbers of num from the interval [minValue,maxValue], and the returned array contains the results.
Where, the random number is created like this: Random ra=new Random(unchecked((int) DateTime.Now.Ticks)); Why not Random ra=new Random(); (the system automatically selects the current time before the random seed)?

It is not safe to seed randomly with system time. If the application is running on a faster computer, the system clock of that computer may not have time to change between calls to this constructor, and the seed values of different instances of Random may be the same. In this case, we need another algorithm to guarantee the randomness of the Numbers generated. So in order to generate enough random Numbers to be "random," we have to use a complicated 1 point method to get a random seed. In the above in this program, we first use the system time as a random seed, and then will generate random number 1 times with loop variables and one is multiplied by the integer parameter related to the system time, in a random seed, and got different random seeds every time, to ensure the produce enough "random" random number.

The function getNum is a 1 recursion, which is used to detect whether the generated random Numbers have duplicates, and if there are duplicates between the extracted Numbers and the obtained Numbers, it will get them randomly again. It is important to note that 1 and 1 random number instances will be generated, so ra will be passed into getNum as a parameter, otherwise the generated Numbers will be repeated.

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 the loop to determine if there is duplication 
{
tmp=ra.Next(minValue,maxValue); // Get it randomly again. 
getNum(arrNum,tmp,minValue,maxValue,ra);// recursive : If there is a repeat between the number and the number obtained, it is retrieved randomly. 
}

}
return tmp;
}

The last thing you want to show is that when you click on one button, the number you get is displayed in one label.

privatevoid button1_Click(object sender, System.EventArgs e)
{
int[] arr=getRandomNum(6,1,20); // from 1 to 20 Remove the 6 A different random number 
int i=0;
string temp="";
while (i<=arr.Length-1){
temp =arr[i].ToString() "";
i ;
}
label1.Text=temp; // Displayed in the label1 In the 
}


Related articles: