RandomHelper.cs 2.3 KB

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