MathUtils.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System.Collections.Generic;
  2. namespace FL
  3. {
  4. public static class MathUtils
  5. {
  6. /// <summary>
  7. /// 传递一个概率值(1-10000),返回随机结果是否在概率内
  8. /// </summary>
  9. /// <param name="probability">1-10000</param>
  10. /// <param name="maxExclusive">最大值</param>
  11. /// <returns></returns>
  12. public static bool Random(int probability, int maxExclusive = 10000)
  13. {
  14. //零固定返回false
  15. if (probability <= 0) return false;
  16. if (probability < maxExclusive)
  17. {
  18. var random = UnityEngine.Random.Range(0, maxExclusive);
  19. return random < probability;
  20. }
  21. return true;
  22. }
  23. /// <summary>
  24. /// 传递一个权重数组,返回随机结果对应的索引
  25. /// </summary>
  26. /// <param name="weights"></param>
  27. /// <returns></returns>
  28. public static int Random(IList<int> weights)
  29. {
  30. var total = 0;
  31. foreach (var weight in weights)
  32. {
  33. total += weight;
  34. }
  35. if (total <= 0)
  36. {
  37. return 0;
  38. }
  39. var random = UnityEngine.Random.Range(0, total);
  40. var temp = 0;
  41. for (var i = 0; i < weights.Count; i++)
  42. {
  43. temp += weights[i];
  44. if (random < temp)
  45. {
  46. return i;
  47. }
  48. }
  49. XGame.Log.Error($"随机数错误。total:{total} total:{random}");
  50. return 0;
  51. }
  52. }
  53. }