C # random generates non-repeating random numbers

Source: Internet
Author: User
Tags random seed

Random class

Namespaces: System

Represents a pseudo-random number generator, a device capable of generating a sequence of numbers that satisfies certain random statistical requirements.

Pseudo-random numbers are selected from a finite set of numbers in the same probability. The selected numbers do not have complete randomness, as they are chosen using a deterministic mathematical algorithm, but from a practical point of view, their randomness is sufficient.

The generation of pseudo-random numbers starts with the seed value. If you use the same seed repeatedly, the same number series will be generated. One way to produce a different sequence is to make the seed value associated with time, thus creating a different series for each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, whereas the parameterized constructor takes the Int32 value based on the number of ticks for the current time. However, because the clock has a limited resolution, if you use the parameterless constructor to create different random objects consecutively, a random number generator that generates the same sequence of random numbers is created.

You can avoid this problem by creating a single object instead of multiple Random objects.

To improve performance, create a random object that can generate multiple random numbers over time, rather than repeating new random objects that generate the same number.

Random Member

Name Description

equals determines whether the specified object is equal to the current object. (Inherit from Object.) )
Finalize allows object to attempt to free resources and perform other cleanup operations before garbage collection reclaims the object. (Inherit from Object.) )
GetHashCode is used as a hash function for a particular type. (Inherit from Object.) )
GetType gets the Type of the current instance. (Inherit from Object.) )
MemberwiseClone creates a shallow copy of the current Object. (Inherit from Object.) )
Next is overloaded. Returns the random number.
Nextbytes fills the elements of the specified byte array with random numbers.
Nextdouble returns a random number between 0.0 and 1.0.
Sample returns a random number between 0.0 and 1.0.
ToString returns a String that represents the current Object. (Inherit from Object.) )

Generate non-repeating random numbers in C #

We can initialize a random number generator in two ways:

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

Random ro = new random ();

The second method can specify an int parameter as a random seed:

int iseed=10;
Random ro = new random (10);
Long tick = DateTime.Now.Ticks;
Random ran = new random ((int) (tick & 0xffffffffL) | (int) (tick >> 32));

This will ensure that 99% is not the same.

After that, we can use the random class object to generate the stochastic number, which is the use of the Random.next () method. This method is quite flexible and you can even specify the upper and lower bounds of the resulting random number.

The use of the upper and lower bounds is not specified as follows:
int Iresult;
Iresult=ro. Next ();

The following code specifies that a random number less than 100 is returned:
int Iresult;
int iup=100;
Iresult=ro. Next (IUP);

The following code specifies that the return value must be within the range of 50-100:
int Iresult;
int iup=100;
int idown=50;
Iresult=ro. Next (IDOWN,IUP);

In addition to the Random.next () method, the random class provides the random.nextdouble () method to produce a random double-precision floating-point number that ranges between 0.0 and 1.0:
Double Dresult;
Dresult=ro. Nextdouble ();

However, using the random class to generate the problem number, there will be duplicates, especially in the small number of topics to generate a non-repetitive problem is difficult.

Refer to some methods on the Internet, find two kinds of solutions, one is to start with a random seed, so that each random seed is different, to ensure that no repetition; the second class uses some data structures and algorithms.

Here are a few ways to introduce the second class:

Method 1: The idea is to use an array to save the index number, randomly generate an array position, and then take the random location of the index number, and copy the last index number to the current array position, and then the upper limit of the random number minus one , specifically, such as: first put the 100 number in an array , each random take a position (the first time is 1-100, the second time is 1-99, ...) ) to replace the number of the position with the last number.

int[] index = new INT[15];
for (int i = 0; i < i++)
index = i;
Random r = new Random ();
Used to save randomly generated 10 number of non-repeating
Int[] result = new INT[10];
int site = 15;//Set upper limit
int id;
for (int j = 0; J <; J + +)
{
id = r.next (1, site-1);
Take a number out of a random position and save it to the result array
RESULT[J] = Index[id];
The last number is copied to the current location
Index[id] = index[site-1];
The upper limit of the position is reduced by one
site--;
}

Method 2: Use Hashtable.

Hashtable Hashtable = new Hashtable ();
Random rm = new random ();
int rmnum = 10;
for (int i = 0; hashtable. Count < Rmnum; i++)
{
int nvalue = RM. Next (100);
if (!hashtable. Containsvalue (nvalue) && Nvalue! = 0)
{
Hashtable. ADD (Nvalue, Nvalue);
Console.WriteLine (Nvalue.tostring ());
}
}

Method 3: Recursive, it is used to detect whether the generated random number is duplicated, if the number taken out and the number obtained has been repeated randomly retrieved.

Random ra=new Random (unchecked ((int) DateTime.Now.Ticks));
Int[] Arrnum=new int[10];
int tmp=0;
int minvalue=1;
int maxvalue=10;
for (int i=0;i<10;i++)
{
Tmp=ra. Next (Minvalue,maxvalue); Random Fetch number
Arrnum=getnum (Arrnum,tmp,minvalue,maxvalue,ra); The value of the fetch is assigned to the array
}
.........
.........
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;
}

C # random generates non-repeating random numbers

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.