SelectorBase.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace Masuit.Tools.RandomSelector;
  5. internal abstract class SelectorBase<T>
  6. {
  7. protected readonly WeightedSelector<T> WeightedSelector;
  8. internal SelectorBase(WeightedSelector<T> weightedSelector)
  9. {
  10. WeightedSelector = weightedSelector;
  11. }
  12. /// <summary>
  13. /// 执行二进制筛选
  14. /// </summary>
  15. internal WeightedItem<T> BinarySelect(List<WeightedItem<T>> items)
  16. {
  17. if (items.Count == 0)
  18. {
  19. throw new InvalidOperationException("没有元素可以筛选");
  20. }
  21. int index = Array.BinarySearch(WeightedSelector.CumulativeWeights, new Random().Next(1, items.Sum(i => i.Weight) + 1));
  22. //如果存在接近的匹配项,二进制搜索返回的负数会比搜索的第1个索引少1。
  23. if (index < 0)
  24. {
  25. index = -index - 1;
  26. }
  27. return items[index];
  28. }
  29. /// <summary>
  30. /// 线性筛选
  31. /// </summary>
  32. /// <param name="items"></param>
  33. /// <returns></returns>
  34. internal WeightedItem<T> LinearSelect(List<WeightedItem<T>> items)
  35. {
  36. // 只对具有允许重复项的多选功能有用,它会随着时间从列表中删除项目。 在这些条件下没有消耗更多性能让二进制搜索起作用。
  37. if (!items.Any())
  38. {
  39. return new WeightedItem<T>(default, 0);
  40. }
  41. var count = 0;
  42. var seed = new Random().Next(1, items.Sum(i => i.Weight) + 1);
  43. foreach (var item in items)
  44. {
  45. count += item.Weight;
  46. if (seed <= count)
  47. {
  48. return item;
  49. }
  50. }
  51. return items.FirstOrDefault();
  52. }
  53. }