RandomGenerator.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using System.Collections.Generic;
  3. using Random = System.Random;
  4. namespace ET
  5. {
  6. // 支持多线程
  7. public static class RandomGenerator
  8. {
  9. [StaticField]
  10. [ThreadStatic]
  11. private static Random random;
  12. private static Random GetRandom()
  13. {
  14. return random ??= new Random(Guid.NewGuid().GetHashCode());
  15. }
  16. public static ulong RandUInt64()
  17. {
  18. int r1 = RandInt32();
  19. int r2 = RandInt32();
  20. return ((ulong)r1 << 32) & (ulong)r2;
  21. }
  22. public static int RandInt32()
  23. {
  24. return GetRandom().Next();
  25. }
  26. public static uint RandUInt32()
  27. {
  28. return (uint) GetRandom().Next();
  29. }
  30. public static long RandInt64()
  31. {
  32. uint r1 = RandUInt32();
  33. uint r2 = RandUInt32();
  34. return (long)(((ulong)r1 << 32) | r2);
  35. }
  36. /// <summary>
  37. /// 获取lower与Upper之间的随机数,包含下限,不包含上限
  38. /// </summary>
  39. /// <param name="lower"></param>
  40. /// <param name="upper"></param>
  41. /// <returns></returns>
  42. public static int RandomNumber(int lower, int upper)
  43. {
  44. int value = GetRandom().Next(lower, upper);
  45. return value;
  46. }
  47. public static bool RandomBool()
  48. {
  49. return GetRandom().Next(2) == 0;
  50. }
  51. public static T RandomArray<T>(T[] array)
  52. {
  53. return array[RandomNumber(0, array.Length)];
  54. }
  55. public static T RandomArray<T>(List<T> array)
  56. {
  57. return array[RandomNumber(0, array.Count)];
  58. }
  59. /// <summary>
  60. /// 打乱数组
  61. /// </summary>
  62. /// <typeparam name="T"></typeparam>
  63. /// <param name="arr">要打乱的数组</param>
  64. public static void BreakRank<T>(List<T> arr)
  65. {
  66. if (arr == null || arr.Count < 2)
  67. {
  68. return;
  69. }
  70. for (int i = 0; i < arr.Count; i++)
  71. {
  72. int index = GetRandom().Next(0, arr.Count);
  73. (arr[index], arr[i]) = (arr[i], arr[index]);
  74. }
  75. }
  76. public static float RandFloat01()
  77. {
  78. int a = RandomNumber(0, 1000000);
  79. return a / 1000000f;
  80. }
  81. }
  82. }