C# random number generator in range, with double,string,bool,relatively unique,without duplicates

Lionsure 2020-01-21 Original by the website

Random numbers are often generated in the development process. For example, when generating a static html web page, the file name is usually got by generating a random number. When generating an order, the order number can also be got by generating a random number.

Random is generally used to generate random numbers in C#. It can arbitrarily specify the range of random numbers. Random combined with array, can generate some special range of random numbers to meet special needs. If a random number is generated in the loop, because the interval is short, the random number generated is the same every time. You need to generate a seed first(there are 3 methods), and then use the seed to generate a random number, or lock the Random object, so as to reduce the repetition rate of generated random numbers. If you want to generate unique random numbers(there are 4 methods), you need to use an array or check whether the generated random numbers are duplicates.

 

I, C# random number generator(Integer random number)

1. Generate a random number with a specified upper limit(such as a random number within 100)

Random rand = new Random();

int n = rand.Next(100);

 

2. C# random number generator between 1 and 10(C# random range)

Random rand = new Random();

int n = rand.Next(1, 10);

 

II, C# random number string and bool

In some cases, random numbers can only take some specified values, such as discontinuous numbers or specified words, etc. At this time, only Random cannot meet the requirements, and it must be implemented by borrowing an array. The implementation idea is probably this: first store these special values in an array, and then use the length of the array as the upper limit of Random to generate a random number. This random number is the index of the array, and the value of the array is obtained according to the index.

(I) C# generate random string

1. Generate discontinuous or specified random numbers

Code show as below:

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

Call:

string[] arr = { "21", "24", "35", "48", "55" };
       GetRandom(arr);

 

2. Generate random numbers for specified words

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

Call:

string[] arr = { "Red", "Green", "Blue", "Black", "White" };
       GetRandom(arr);

 

(II) Generate C# random bool

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

Call:

Response.Write(GenerateBoolRandomNumber()); // The result is true

 

 

III, C# random double generator

You can only generate arbitrary decimal random numbers in C# by default. If you want to generate a decimal random number with a specified range, you need to write the code. When writing code, you can encapsulate them into a method or a class, which can override C#'s NextDouble() method

1. Encapsulating code into a method

A. Generate arbitrary decimal random numbers(C# random range)

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

Call:

Random rand = new Random();
       double randNumber = NextDouble(rand, 1.38, 3.66);
       Response.Write(randNumber); // The result is 2.86331357713943

 

B. Generate a random number with a specified number of decimal places(e.g. 2 decimal places)

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

Call:

Random rand = new Random();
       double randNumber = NextDouble(rand, 7.25, 8.76, 2); // Round to 2 decimal places
       Response.Write(randNumber); // The result is 7.61

 

2. Encapsulating code into a class

Code:

using System;
       using System.Text;

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

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

Call:

Random rand = new Random();
       double randNumber1 = rand.NextDouble(5.16, 8.68);
       double randNumber2 = rand.NextDouble(5.16, 8.68, 2); // Round to 2 decimal places
       Response.Write(randNumber1 + "; " + randNumber2); // The result are 6.18547231617639; 7.36

 

IV, Generate relatively unique random numbers

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-repeating random numbers, you need to use seed or lock the Random object. Here are their Implementation.

1. Use seed to generate relatively non-repeating random numbers

Generate seed method 1:

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

Generate random numbers from 1 to 10: 2, 5, 2, 5, 7, 3, 4, 4, 6, 3

 

Generate seed method 2:

using System.Text.RegularExpressions;

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

Generate random numbers from 1 to 10: 1, 7, 4, 9, 8, 1, 8, 7, 9, 8

 

Generate seed method 3:

using System.Security.Cryptography;

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

Generate random numbers from 1 to 10: 4, 8, 7, 2, 6, 7, 6, 5, 5, 7

 

Generate a specified number of random numbers and store them in an array(C# random range):

// randNumber is the number of random numbers
    public int[] GenerateRandomNumber(int minValue, int maxValue, int randNumber)
    {
        Random rand = new Random(GenerateSeed());
        int[] arr = new int[randNumber];

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

Call:

int[] arr = GenerateRandomNumber(1, 10, 10);
       string s = string.Empty;
       for (int i = 0; i < arr.Length; i++)
       {
              s += arr[i].ToString() + ", ";
       }
       Response.Write(s);

 

2. Generate relatively unique random numbers by locking Random object

Code:

public int GenerateRandomNumber(Random rand, int minValue, int maxValue)
       {
              lock (rand) // lock Random object
              {
                     return rand.Next(minValue, maxValue);
              }
       }

Call:

int[] arr = new int[5];
       Random rand = new Random();
       for (int i = 0; i < 5; i++)
       {
              arr[i] = GenerateRandomNumber(rand, 1, 10); // The result are 5, 7, 2, 5, 2
        }

 

 

V, C# unique random number generator(Random number generator without duplicates c#, with C# get random number in range)

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

Code:

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

       int maxIndex = maxValue - minValue + 2; // The Upper Limit of index Array
              int[] indexArray = new int[maxIndex];
              for (int i = 0; i < maxIndex; i++)
              {
                     indexArray[i] = minValue - 1;
                     minValue++;
              }

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

                      // Take a number from the index array and save it to the array of random number according to the index
                     randNumber[j] = indexArray[index];

                      // Replace the number that has been selected as a random number with the last number in the index array
                     indexArray[index] = indexArray[maxIndex - 1];
                     maxIndex--; // The Upper Limit of the index minus 1
              }
              return randNumber;
       }

Call:

GenerateUniqueRandomNumber(1, 10, 10); The result are 9, 5, 10, 1, 7, 3, 2, 4, 6, 8

GenerateUniqueRandomNumber(1, 10, 5); // The result are 3, 7, 6, 1, 9

 

2. Method 2: Generate non-repeating random numbers with a do...while loop, and check whether the generated random numbers are duplicates with a for loop. Only non-repeating random numbers are saved to the array.

Code:

// n is the number of random numbers generated
       public int[] GenerateUniqueRandomNumber(int minValue, int maxValue, int n)
       {
               // Random.Next(1, 10) can only generate random numbers up to 9, if you want to generate random numbers up to 10, add 1 to maxValue
              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;

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

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

// Check if the currently generated random number is a duplicate
       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:

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

GenerateUniqueRandomNumber(1000, 1100, 6); // Generate 4 digit unique random number in c#, the result are 1008, 1039, 1080, 1030, 1023, 1092

 

3. Method 3: Check whether the generated random numbers are duplicates with a do...while loop. Only non-repeating random numbers are saved to the Hashtable.

Code:

using System.Collections;

// n is the number of random numbers generated
       public Hashtable GenerateUniqueRandomNumber(int minValue, int maxValue, int n)
       {
               // Random.Next(1, 10) can only generate random numbers up to 9, if you want to generate random numbers up to 10, add 1 to maxValue
              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 rand = new Random((int)DateTime.Now.Ticks);

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

Call:

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

 

// Generate 4 digit unique random number in c#, the result are 1041, 1049, 1012, 1014, 1095, 1074
       GenerateUniqueRandomNumber(1000, 1100, 6);

 

4. Method 4: Generate unique random numbers with Linq

Code:

using System.Linq;

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

Call:

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

The above methods for generating a specified random number have passed the test and can be flexibly selected according to the actual development needs. Generally, Random is sufficient.