Use C# to generate unique random numbers - asp.net tutorial

巴扎黑
Release: 2016-12-20 16:59:16
Original
1197 people have browsed it

When we are building an examination system that can automatically generate test papers, we often need to randomly generate a set of non-repeating questions. The .net Framework provides a class System.Random specifically used to generate random numbers.
 As for random numbers, everyone knows that it is impossible for a computer to generate completely random numbers. The so-called random number generator uses a certain algorithm to perform complex operations on pre-selected random seeds, and uses the generated results to approximate simulations. Completely random numbers are called pseudo-random numbers. Pseudo-random numbers are chosen from a finite set of numbers with equal probability. The numbers chosen are not completely random, but they are random enough for practical purposes. The selection of pseudo-random numbers starts from random seeds, so in order to ensure that the pseudo-random numbers obtained each time are sufficiently "random", the selection of random seeds is very important. If the random seeds are the same, the random numbers generated by the same random number generator will also be the same. Generally, we use parameters related to the system time as the random seed, which is also the default method used by the random number generator in the .net Framework.
 We can initialize a random number generator in two ways:
 The first method does not specify a random seed, the system automatically selects the current time as the random seed:
 Random ro = new Random();
 The second method can specify a Int type parameter as 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 can guarantee that 99% of them are not the same.
 After that, we can use this Random class object to generate random numbers. At this time, we need to use the Random.Next() method. This method is quite flexible, and you can even specify upper and lower limits for the random numbers generated.
 The usage without specifying upper and lower limits is as follows:
 int iResult;
 iResult=ro.Next();
 The following code specifies the return of a random number less than 100:
 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 also provides the Random.NextDouble() method to generate a random double-precision floating point number in the range of 0.0-1.0:
 double dResult;
 dResult=ro. NextDouble();
But using the Random class to generate question numbers will cause duplication. Especially in a small number of questions, it is difficult to generate non-duplicate questions. I refer to some methods on the Internet, including two categories, one The first type starts with random seeds, so that each random seed is different to ensure no repetition; the second type uses some data structures and algorithms. The following mainly introduces several methods for the second category.
 
Method 1: The idea is to use an array to save the index number, first randomly generate an array position, then take out the index number of this position, and copy the last index number to the current array position, and then make the random number The upper limit is reduced by one, specifically: first put these 100 numbers in an array, randomly pick a position each time (the first time is 1-100, the second time is 1-99,...), and change the position The number is replaced with the last number.

 int[] index = new int[15];
 for (int i = 0; i < 15; i++)
 index = i;
 Random r = new Random();
  //Used to save random generation 10 unique numbers
 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);
   //Take out a number at a random position and save it to the result array
  result[j] = index[id];
   //Copy the last number to the current position
index[id] = index[site - 1];
   //The lower limit of the position is reduced by one
  site--;
 }

 Method 2: Use Hashtable. [NextPage]

 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: Recursion, use it to detect whether the generated random numbers are duplicated. If the numbers taken out are duplicates of the numbers already obtained, obtain them randomly 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); //Randomly pick a number
  arrNum=getNum(arrNum,tmp,minValue,maxValue,ra); / / Take out the value and assign it 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 a loop to determine whether there are duplicates
   {
    tmp=ra.Next (minValue,maxValue); //Re-obtain randomly.
   getNum(arrNum,tmp,minValue,maxValue,ra);//Recursion: If the number taken out is the same as the number already obtained, it will be randomly obtained again.
   }
  n++;
  }
   return tmp;
 }


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template