The C implementation randomizes an array of class instances
- 2020-12-26 05:52:07
- OfStack
This article is an example of an C# implementation that randomizes arrays of classes. Share to everybody for everybody reference. The details are as follows:
This is a class that extends the C# random number generator. It can randomly generate a specified range of numbers. It can randomly sort arrays
using System;
namespace DotNet.Utilities
{
/// <summary>
/// use Random The class generates pseudo-random numbers
/// </summary>
public class RandomHelper
{
// Random number object
private Random _random;
#region The constructor
/// <summary>
/// The constructor
/// </summary>
public RandomHelper()
{
// Assign a value to a random number object
this._random = new Random();
}
#endregion
#region generate 1 Number of random integers in the specified range
/// <summary>
/// generate 1 Six random integers with a specified range that includes a minimum but does not include a maximum
/// </summary>
/// <param name="minNum"> The minimum value </param>
/// <param name="maxNum"> The maximum </param>
public int GetRandomInt(int minNum, int maxNum)
{
return this._random.Next(minNum, maxNum);
}
#endregion
#region generate 1 a 0.0 to 1.0 Random decimal of
/// <summary>
/// generate 1 a 0.0 to 1.0 Random decimal of
/// </summary>
public double GetRandomDouble()
{
return this._random.NextDouble();
}
#endregion
#region right 1 The array is sorted randomly
/// <summary>
/// right 1 The array is sorted randomly
/// </summary>
/// <typeparam name="T"> Type of array </typeparam>
/// <param name="arr"> An array that needs to be sorted randomly </param>
public void GetRandomArray<T>(T[] arr)
{
// An algorithm for randomizing arrays : Randomly select two positions and swap the values at the two positions
// Number of exchanges , The length of the array is used here as the number of exchanges
int count = arr.Length;
// Began to exchange
for (int i = 0; i < count; i++)
{
// Generate two random number locations
int randomNum1 = GetRandomInt(0, arr.Length);
int randomNum2 = GetRandomInt(0, arr.Length);
// Define temporary variables
T temp;
// Swap the values of two random number locations
temp = arr[randomNum1];
arr[randomNum1] = arr[randomNum2];
arr[randomNum2] = temp;
}
}
#endregion
}
}
Hopefully this article has helped you with your C# programming.