[C#] C#封装类对数组进行随机排序 →→→→→进入此内容的聊天室

来自 , 2019-03-30, 写在 C#, 查看 126 次.
URL http://www.code666.cn/view/4b3acf48
  1. using System;
  2.  
  3. namespace DotNet.Utilities
  4. {
  5.     /// <summary>
  6.     /// 使用Random类生成伪随机数
  7.     /// </summary>
  8.     public class RandomHelper
  9.     {
  10.         //随机数对象
  11.         private Random _random;
  12.  
  13.         #region 构造函数
  14.         /// <summary>
  15.         /// 构造函数
  16.         /// </summary>
  17.         public RandomHelper()
  18.         {
  19.             //为随机数对象赋值
  20.             this._random = new Random();
  21.         }
  22.         #endregion
  23.  
  24.         #region 生成一个指定范围的随机整数
  25.         /// <summary>
  26.         /// 生成一个指定范围的随机整数,该随机数范围包括最小值,但不包括最大值
  27.         /// </summary>
  28.         /// <param name="minNum">最小值</param>
  29.         /// <param name="maxNum">最大值</param>
  30.         public int GetRandomInt(int minNum, int maxNum)
  31.         {
  32.             return this._random.Next(minNum, maxNum);
  33.         }
  34.         #endregion
  35.  
  36.         #region 生成一个0.0到1.0的随机小数
  37.         /// <summary>
  38.         /// 生成一个0.0到1.0的随机小数
  39.         /// </summary>
  40.         public double GetRandomDouble()
  41.         {
  42.             return this._random.NextDouble();
  43.         }
  44.         #endregion
  45.  
  46.         #region 对一个数组进行随机排序
  47.         /// <summary>
  48.         /// 对一个数组进行随机排序
  49.         /// </summary>
  50.         /// <typeparam name="T">数组的类型</typeparam>
  51.         /// <param name="arr">需要随机排序的数组</param>
  52.         public void GetRandomArray<T>(T[] arr)
  53.         {
  54.             //对数组进行随机排序的算法:随机选择两个位置,将两个位置上的值交换
  55.  
  56.             //交换的次数,这里使用数组的长度作为交换次数
  57.             int count = arr.Length;
  58.  
  59.             //开始交换
  60.             for (int i = 0; i < count; i++)
  61.             {
  62.                 //生成两个随机数位置
  63.                 int randomNum1 = GetRandomInt(0, arr.Length);
  64.                 int randomNum2 = GetRandomInt(0, arr.Length);
  65.  
  66.                 //定义临时变量
  67.                 T temp;
  68.  
  69.                 //交换两个随机数位置的值
  70.                 temp = arr[randomNum1];
  71.                 arr[randomNum1] = arr[randomNum2];
  72.                 arr[randomNum2] = temp;
  73.             }
  74.         }
  75.         #endregion
  76.     }
  77. }
  78.  
  79. //csharp/8645

回复 "C#封装类对数组进行随机排序"

这儿你可以回复上面这条便签

captcha