SoFunction
Updated on 2025-03-08

C# implements random sorting of arrays

This article describes the C# implementation of random sorting of arrays. Share it for your reference. The details are as follows:

This class that expands the C# random number generator can randomly generate numbers in a specified range and can randomly sort arrays, which is very useful

using System;
namespace 
{
  /// <summary>
  /// Generate pseudo-random numbers using Random class  /// </summary>
  public class RandomHelper
  {
    //Random number object    private Random _random;
    #region constructor    /// <summary>
    /// Constructor    /// </summary>
    public RandomHelper()
    {
      // Assign values ​​to random number objects      this._random = new Random();
    }
    #endregion
    #region Generates a random integer with a specified range    /// <summary>
    /// Generate a random integer of the specified range, which includes the minimum value but does not include the maximum value    /// </summary>
    /// <param name="minNum">Minimum value</param>    /// <param name="maxNum">Maximum value</param>    public int GetRandomInt(int minNum, int maxNum)
    {
      return this._random.Next(minNum, maxNum);
    }
    #endregion
    #region Generates a random decimal from 0.0 to 1.0    /// &lt;summary&gt;
    /// Generate a random decimal from 0.0 to 1.0    /// &lt;/summary&gt;
    public double GetRandomDouble()
    {
      return this._random.NextDouble();
    }
    #endregion
    #region Randomly sorting an array    /// &lt;summary&gt;
    /// Randomly sort an array    /// &lt;/summary&gt;
    /// <typeparam name="T">Array type</typeparam>    /// <param name="arr">Arrays that require random sorting</param>    public void GetRandomArray&lt;T&gt;(T[] arr)
    {
      //Algorithm for random sorting of arrays: randomly select two positions and exchange values ​​at the two positions.      //The number of exchanges, the length of the array is used as the number of exchanges      int count = ;
      //Start the exchange      for (int i = 0; i &lt; count; i++)
      {
        //Generate two random number positions        int randomNum1 = GetRandomInt(0, );
        int randomNum2 = GetRandomInt(0, );
        //Define temporary variables        T temp;
        //Swap the values ​​of two random numbers positions        temp = arr[randomNum1];
        arr[randomNum1] = arr[randomNum2];
        arr[randomNum2] = temp;
      }
    }
    #endregion
  }
}

I hope this article will be helpful to everyone's C# programming.