SelectorBase.cs 1.9 KB

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