C # several methods of generating random numbers (integer, decimal, character, Boolean, relatively non repetitive and unique) in a specified range

In C #, Random numbers are generally generated by Random, which can arbitrarily specify the range of Random numbers.

Random combined with array can generate some random numbers in a special range to meet special needs. If a random number is generated in the loop, because the interval is short, the random number generated each time is the same. You need to generate a seed (there are three methods), and then use the seed to generate a random number, or lock the random object, so as to reduce the repetition rate of generating a random number. If you want to generate a unique random number (there are four methods), you need to use an array or check whether the generated random number is repeated.

1, Generate Random numbers (integer Random numbers) in the specified range with Random

1. Generate a random number with a specified upper limit (e.g. generate a random number within 100)

Random ran = new Random();
int n = ran.Next(100);

2. Generate random numbers with specified upper and lower limits (e.g. generate random numbers from 100 to 1000)

Random ran = new Random();
int n = ran.Next(100, 1000);

2, Generate Random numbers (character and Boolean Random numbers) in the specified range by combining Random with array

In some cases, Random numbers can only take some specially specified values, such as discontinuous numbers or specified words. At this time, only Random can not meet the requirements, and can only be realized by borrowing the array.
The implementation idea is roughly as follows: first save these special values in the array, and then take the length of the array as the upper limit of Random to generate a Random number. This Random number is the subscript of the array, and obtain the value of the array according to the subscript.

(1) Generate character random number

1. A random number that produces a discontinuity or a specified value

public string GetRandom(string[] arr)
{
Random ran = new Random();
int n = ran.Next(arr.Length - 1);
return arr[n];
}

//Call method:
string[] arr = { "25", "28", "30", "50", "60" };
GetRandom(arr);

2. Generates a random number that retains the specified number of decimal places (for example, 2 digits)

If you want to use the specified word as the value of the random number, the code implementation is the same as the above example, the only difference is the value of the random number, so just define a word array and call the above code directly.
Call method:

string[] arr = { "red", "green", "blue", "orange", "white" };
GetRandom(arr);

(2) Generate boolean random number

public bool GenerateBoolRandom()
{
bool[] arr = { true, false };
Random ran = new Random();
return arr[ran.Next(2)];
}

//Call method:
Response.Write(GenerateBoolRandom());// Result true

3, Generating decimal Random numbers with Random

By default, C# can only generate arbitrary decimal random numbers. If you want to generate decimal random numbers in a specified range, you need to write your own code. When writing code, you can encapsulate them into either a method or a class, which can overload C#'s NextDouble() method.

1. Encapsulate code into a method

A. Generate decimal random number

public double NextDouble(Random ran, double minValue, double maxValue)
{
return ran.NextDouble() * (maxValue - minValue) + minValue;
}

//Call:

Random ran = new Random();
double randNum = NextDouble(ran, 1.52, 2.65);
Response.Write(randNum);// Result 2.3092776811112

B. Generates a random number that retains the specified number of decimal places (for example, 2 digits)

public double NextDouble(Random ran, double minValue, double maxValue, int decimalPlace)
{
double randNum = ran.NextDouble() * (maxValue - minValue) + minValue;
return Convert.ToDouble(randNum.ToString("f" + decimalPlace));
}

//Call:
Random ran = new Random();
double randNum = NextDouble(ran, 5.16, 8.68, 2);// Keep two decimal places
Response.Write(randNum);// Outcome 8.46

2. Encapsulate the code into a class

using System;
using System.Text;

public static class RandomDoubleRange
{
public static double NextDouble(this Random ran, double minValue, double maxValue)
{
return ran.NextDouble() * (maxValue - minValue) + minValue;
}

public static double NextDouble(this Random ran, double minValue, double maxValue, int decimalPlace)
{
double randNum = ran.NextDouble() * (maxValue - minValue) + minValue;
return Convert.ToDouble(randNum.ToString("f" + decimalPlace));
}
}

//Call:
Random ran = new Random();
double randNum1 = ran.NextDouble(5.16, 8.68);
double randNum2 = ran.NextDouble(5.16, 8.68, 2);//Keep two decimal places
Response.Write(randNum1 + "; " + randNum2);//Results 7.41055195257559; six point six nine

4, Produces a relatively non repeating random number

When generating random numbers in a loop, because the time interval for generating random numbers is relatively short, it is easy to generate repeated random numbers. If you want to generate non repeated random numbers, you need to use seeds or lock the random number object. The following is their implementation method.

1. Use seeds to generate relatively non repetitive random numbers

Seed generation method 1:

public static int GenerateRandomSeed()
{
return (int)DateTime.Now.Ticks;
}

//The random numbers from 1 to 10 are: 2, 5, 2, 5, 7, 3, 4, 4, 6, 3

Seed generation method 2:

using System.Text.RegularExpressions;

public static int GenerateRandomSeed()
{
return Convert.ToInt32(Regex.Match(Guid.NewGuid().ToString(), @"\d+").Value);
}

//The random numbers from 1 to 10 are: 1, 7, 4, 9, 8, 1, 8, 7, 9, 8

Seed generation method 3:

using System.Security.Cryptography;

public static int GenerateRandomSeed()
{
byte[] bytes = new byte;
RNGCryptoServiceProvider rngCSP = new RNGCryptoServiceProvider();
rngCSP.GetBytes(bytes);
return BitConverter.ToInt32(bytes, 0);
}

//The random numbers from 1 to 10 are: 4, 8, 7, 2, 6, 7, 6, 5, 5, 7

Generate a specified number of random numbers and coexist them into the array:

// randNum is the number of random numbers generated
public int[] GenerateRandom(int minValue, int maxValue, int randNum)
{
Random ran = new Random(GenerateRandomSeed());
int[] arr = new int[randNum];

for (int i = 0; i < randNum; i++)
{
arr[i] = ran.Next(minValue, maxValue);
}
return arr;
}

//Call method:
int[] arr = GenerateRandom(1, 10, 10);
string temp = string.Empty;
for (int i = 0; i < arr.Length; i++)
{
temp += arr[i].ToString() + ", ";
}
Response.Write(temp);

2. Generate a relatively non repeating Random number by locking the Random object

Generate random number:

public int GenerateRandom(Random ran, int minValue, int maxValue)
{
lock (ran) // Lock Random object
{
return ran.Next(minValue, maxValue);
}
}

//Call:
int[] arr = new int;
Random ran = new Random();
for (int i = 0; i < 5; i++)
{
arr[i] = GenerateRandom(ran, 1, 10);// Results 5, 7, 2, 5, 2
}

5, Generates a specified range of random numbers that are absolutely non repetitive

1. Method 1: make an index array, and then take the generated random number as the index, and take a number from the array as the random number.

Generate random number:

// n is the number of generated random numbers
public int[] GenerateUniqueRandom(int minValue, int maxValue, int n)
{
//If the number of generated random numbers is greater than the total number of numbers in the specified range, only the total number of numbers in the range can be generated at most
if (n > maxValue - minValue + 1)
n = maxValue - minValue + 1;

int maxIndex = maxValue - minValue + 2;// Index array upper limit
int[] indexArr = new int[maxIndex];
for (int i = 0; i < maxIndex; i++)
{
indexArr[i] = minValue - 1;
minValue++;
}

Random ran = new Random();
int[] randNum = new int[n];
int index;
for (int j = 0; j < n; j++)
{
index = ran.Next(1, maxIndex - 1);// Generate a random number as an index

//Take a number from the index array according to the index and save it to the random number array
randNum[j] = indexArr[index];

// Replaces the number that has been selected as a random number with the last number in the index array
indexArr[index] = indexArr[maxIndex - 1];
maxIndex--; //Index upper limit minus 1
}
return randNum;
}

//Call method:

GenerateUniqueRandom(1, 10, 10);// Results 9, 5, 10, 1, 7, 3, 2, 4, 6, 8

GenerateUniqueRandom(1, 10, 5);// Results 3, 7, 6, 1, 9

2. Method 2: use do The while loop is used to generate non repeating random numbers, and the for loop is used to check whether the generated random numbers are repeated. Only non repeating random numbers are saved to the array.

Generate random number:

// n number of random numbers generated
public int[] GenerateUniqueRandom(int minValue, int maxValue, int n)
{
// Random.Nex(1, 10) can only generate random numbers up to 9. To generate random numbers up to 10, maxValue must be increased by 1
maxValue++;

// Random. NEX (n) cannot be greater than 10, so it can only generate 10 random numbers
if (n > maxValue - minValue)
n = maxValue - minValue;

int[] arr = new int[n];
Random ran = new Random((int)DateTime.Now.Ticks);

bool flag = true;
for (int i = 0; i < n; i++)
{
do
{
int val = ran.Next(minValue, maxValue);
if (!IsDuplicates(ref arr, val))
{
arr[i] = val;
flag = false;
}
} while (flag);
if (!flag)
flag = true;
}
return arr;
}

// Check whether the currently generated random number is repeated
public bool IsDuplicates(ref int[] arr, int currRandNum)
{
bool flag = false;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == currRandNum)
{
flag = true;
break;
}
}
return flag;
}

//Call method:

int[] arr = GenerateUniqueRandom(1, 10, 10);// Generate 10 random numbers from 1 to 10
for (int i = 0; i < arr.Length; i++)
Response.Write(arr[i] + ", ");// Results 10, 7, 9, 4, 3, 5, 1, 2, 6, 8

GenerateUniqueRandom(1, 10, 5);// Generate 5 random numbers from 1 to 10, and the results are 9, 1, 7, 2 and 10

3. Method 3: use do While loop to check whether the generated random number is repeated. Only non repeated random numbers are saved to the hash table.

Generate random number:

using System.Collections;

// n is the number of generated random numbers
public Hashtable GenerateUniqueRandom(int minValue, int maxValue, int n)
{
// Random.Next(1, 10) can only generate random numbers up to 9. To generate random numbers up to 10, maxValue needs to be increased by 1
maxValue++;

// Random.Next(1, 10) can only generate 9 random numbers, so n cannot be greater than 10 - 1
if (n > maxValue - minValue)
n = maxValue - minValue;

Hashtable ht = new Hashtable();
Random ran = new Random((int)DateTime.Now.Ticks);

bool flag = true;
for (int i = 0; i < n; i++)
{
do
{
int val = ran.Next(minValue, maxValue);
if (!ht.ContainsValue(val))
{
flag = false;
}
} while (flag);
if (!flag)
flag = true;
}
return ht;
}

//Call method:

Hashtable ht = GenerateUniqueRandom(1, 10, 10);// Generate 10 random numbers from 1 to 10
foreach (DictionaryEntry de in ht)
Response.Write(de.Value.ToString() + ", ");// Results 10, 7, 9, 4, 3, 5, 1, 2, 6, 8

GenerateUniqueRandom(1, 10, 5);// Generate 5 random numbers from 1 to 10, and the results are 4, 10, 9, 7 and 6

4. Method 4: generate non repeated random numbers with Linq

Generate random number:

using System.Linq;

public IEnumerable<int>
GenerateNoDuplicateRandom(int minValue, int maxValue)
{
return Enumerable.Range(minValue, maxValue).OrderBy(g => Guid.NewGuid());
}

//Call method:

IEnumerable<int> list = GenerateNoDuplicateRandom(1, 10);
string str = string.Empty;
foreach (int item in list)
{
str += item.ToString() + ", ";
}
Response.Write(str);// Results 5, 2, 10, 1, 7, 6, 8, 3, 9, 4

The above methods for generating specified Random numbers have passed the test and can be flexibly selected according to the actual development needs. Generally, Random is used directly.

Added by richtom80 on Sat, 15 Jan 2022 13:29:23 +0200