# C # Generate random numbers

Source: Internet
Author: User
Tags random seed

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, use it to prevent boring people in the forum to fill the water may also be used to encrypt information and so on. This article discusses how to randomly generate several distinct random numbers within a range of numbers, such as randomly generating 6 distinct integers from 1 to 20, and using this article to describe the use of random numbers in Visual C #.
. Net. Frameword provides a class system.random that generates random numbers, which are imported by default and can be used directly during programming. We know that the computer does not produce a completely random number, the resulting number is called a pseudo-random number, it is the same probability from a limited set of numbers, the selected number is not completely random, but in practical terms, its randomness is sufficient.

We can initialize a random number generator in the following two ways;

Functions are used such as random numbers from 100 to 999

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

However, this will be repeated, you can give random a system time as a parameter, in order to generate a number of randomly, it will not repeat

The first method does not specify a random seed, and the system automatically selects the current time before the random seed:

Random ra=new random ();

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

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

Below we will use the Random.next () method to generate a random number.

Ra. Next ();

It returns a number that is greater than or equal to zero and less than 2,147,483,647, which does not satisfy our needs, and we introduce its overloaded functions and some other methods.

public virtual int Next (int);

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

public virtual int Next (int minValue, int maxValue);

Usage: Ra.next (1,20)
Returns a random number within a specified range (here is 1-20), which we will use in the following instance.

There are several other methods of class system.random, namely:
Public methods:
Nextbytes fills the elements of the specified byte array with random numbers.
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 be accessed.

The above describes the basic use of random numbers, below we use an example to do a further introduction. To randomly generate several distinct random numbers within a range of numbers, such as randomly generating 6 distinct integers from 1 to 20.

The main is the following two functions Getrandomnum and Getnum:

Public int[] Getrandomnum (int num,int minvalue,int maxValue)
{
Random ra=new Random (unchecked ((int) DateTime.Now.Ticks));
Int[] Arrnum=new Int[num];
int tmp=0;
for (int i=0;i<=num-1;i) {
Tmp=ra. Next (Minvalue,maxvalue); Random Fetch number
Arrnum[i]=getnum (Arrnum,tmp,minvalue,maxvalue,ra); The value of the fetch is assigned to the array
}
return arrnum;
}

The getrandomnum is the interval [minvalue,maxvalue] that takes out NUM's distinct random number, and the returned array contains the result.

Where the random number is created in this way is the 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 use system time for random seeds, and 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 the different instances of random may be the same. In this case, we need additional algorithms to guarantee the randomness of the resulting numbers. So in order to ensure that the random number generated is "random" enough, we have to use a more complex method to get random seeds. In the above procedure, we first use the system time as a random seed, and then multiply the last generated random number with a loop variable and an integer parameter related to the system time as a random seed, thus obtaining a random seed that is different each time, which guarantees that a random number with enough "random" is generated.

The function getnum is a recursive, used to detect whether the generated random number is duplicated, and if the number taken out and the number obtained is duplicated, it is re-randomly obtained. It is important to note that a random number instance is generated together so that the RA is passed into the getnum as a parameter, otherwise the resulting number will be duplicated.

public int 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 if there are duplicates
{
Tmp=ra. Next (Minvalue,maxvalue); Re-randomly acquired.
Getnum (Arrnum,tmp,minvalue,maxvalue,ra);//recursion: If the number that is taken out and the number obtained is duplicated, it is retrieved randomly.
}
n;
}
return TMP;
}

The last thing to show is that the number taken when a button is clicked is displayed in a label.

private void Button1_Click (object sender, System.EventArgs e)
{
Int[] Arr=getrandomnum (6,1,20); Remove 6 distinct 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 the Label1
}

C # Generate random numbers

Related Keywords:
Related Article

### 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.