Use C # To generate random numbers that are not repeated

Source: Internet
Author: User
Tags random seed

when creating an examination system that can automatically generate a test, we often need to randomly generate a group of non-duplicate questions. net Framework provides a class system dedicated to generating random numbers. random.
as we all know about random numbers, computers cannot generate completely random numbers, the so-called random number generator uses a certain algorithm to perform complex operations on the pre-selected random seed, use the generated results to simulate a completely random number, which is called a pseudo-random number. A pseudo-random number is selected from a finite number with the same probability. The selected number is not completely random, but from a practical point of view, the random degree is enough. The selection of pseudo-random numbers starts with the random seed. To ensure that each pseudo-random number obtained is "random" enough, the selection of Random Seed is very important. If the random seed is the same, the random number generated by the same random number generator will also be the same. Generally, we use parameters related to system time as random seeds, which is also the default method used by the random number generator in. NET Framework.
WE can initialize a random number generator in two ways:
the first method does not specify the random seed. The system automatically selects the current time as the 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 & 0 xffffffffl) | (INT) (tick> 32);
this ensures that 99% is not the same.
then, we can use the random class object to generate a random number. In this case, the random. Next () method is used. This method is quite flexible. You can even specify the upper and lower limits of the generated random number.
the upper and lower limits are not specified as follows:
int iresult;
iresult = Ro. next ();
the Code below specifies to return a random number less than 100:
int iresult;
int iup = 100;
iresult = Ro. next (iup);
The following Code specifies that the returned value must be within the range of 50-100:
int iresult;
int iup =;
int idown = 50;
iresult = Ro. next (idown, iup);
except for random. in addition to the next () method, the random class also provides the random. the nextdouble () method generates a random double-precision floating point number ranging from 0.0 to 1.0:
double dresult;
Dresult = Ro. nextdouble ();
but when you use the random class to generate question numbers, there will be duplicates, especially in the case of a small number of questions, which is difficult to generate non-repeated questions, I have referred to some methods on the Internet, including two types. One is to start with a random seed, so that each random seed is different to ensure no repetition; the second type uses some data structures and algorithms. The following describes several methods in the second type. Feedom.net
Method 1: The idea is to use an array to save the index number. First, a random array location is generated, and then the index number at this location is obtained, copy the last index number to the current array location, and then reduce the upper limit of the random number by one. For example, first place the 100 number in a number group, each time a random location (the first time is 1-100, the second time is 1-99 ,...), replace the number at this position with the last number.
China Network Management Forum bbs.bitscn.com

Int [] Index = new int [15];
For (INT I = 0; I <15; I ++)
Index = I;
Random r = new random ();
// Stores the number of randomly generated records that are not repeated.
Int [] result = new int [10];
Int site = 15; // set the lower limit
Int ID;
For (Int J = 0; j <10; j ++)
{
Id = R. Next (1, site-1 );
// Retrieve a random number and save it to the result array.
Result [J] = index [ID];
// Copy the last number to the current position
Index [ID] = index [site-1];
// Reduce the minimum position by one
Site --;
}

China Network Management Alliance www_bitscn_com

Method 2: Use hashtable. [Nextpage]

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 ());
}
}

China Network Management Forum bbs.bitscn.com

Method 3: recursion. 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.

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 count
Arrnum = getnum (arrnum, TMP, minvalue, maxvalue, RA); // The retrieved value 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 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. China Network Management Alliance WWW, bitscn, com
}
N ++;
}
Return TMP;
}

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.