|
@@ -7,18 +7,16 @@ namespace Masuit.Tools.RandomSelector.Algorithm
|
|
|
internal abstract class SelectorBase<T>
|
|
|
{
|
|
|
protected readonly WeightedSelector<T> WeightedSelector;
|
|
|
- private readonly System.Random _rng;
|
|
|
|
|
|
internal SelectorBase(WeightedSelector<T> weightedSelector)
|
|
|
{
|
|
|
WeightedSelector = weightedSelector;
|
|
|
- _rng = new System.Random();
|
|
|
}
|
|
|
|
|
|
protected int GetSeed(List<WeightedItem<T>> items)
|
|
|
{
|
|
|
- var TopRange = items.Sum(i => i.Weight) + 1;
|
|
|
- return _rng.Next(1, TopRange);
|
|
|
+ var sum = items.Sum(i => i.Weight) + 1;
|
|
|
+ return new Random().Next(1, sum);
|
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
@@ -31,8 +29,8 @@ namespace Masuit.Tools.RandomSelector.Algorithm
|
|
|
throw new InvalidOperationException("没有元素可以筛选");
|
|
|
}
|
|
|
|
|
|
- var Seed = GetSeed(items);
|
|
|
- return BinarySearch(items, Seed);
|
|
|
+ var seed = GetSeed(items);
|
|
|
+ return BinarySearch(items, seed);
|
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
@@ -46,8 +44,8 @@ namespace Masuit.Tools.RandomSelector.Algorithm
|
|
|
throw new InvalidOperationException("没有元素可以筛选");
|
|
|
}
|
|
|
|
|
|
- var Seed = GetSeed(items);
|
|
|
- return LinearSearch(items, Seed);
|
|
|
+ var seed = GetSeed(items);
|
|
|
+ return LinearSearch(items, seed);
|
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
@@ -58,13 +56,13 @@ namespace Masuit.Tools.RandomSelector.Algorithm
|
|
|
/// <returns></returns>
|
|
|
private WeightedItem<T> LinearSearch(IEnumerable<WeightedItem<T>> items, int seed)
|
|
|
{
|
|
|
- var RunningCount = 0;
|
|
|
- foreach (var Item in items)
|
|
|
+ var count = 0;
|
|
|
+ foreach (var item in items)
|
|
|
{
|
|
|
- RunningCount += Item.Weight;
|
|
|
- if (seed <= RunningCount)
|
|
|
+ count += item.Weight;
|
|
|
+ if (seed <= count)
|
|
|
{
|
|
|
- return Item;
|
|
|
+ return item;
|
|
|
}
|
|
|
}
|
|
|
|
|
@@ -79,15 +77,15 @@ namespace Masuit.Tools.RandomSelector.Algorithm
|
|
|
/// <returns></returns>
|
|
|
private WeightedItem<T> BinarySearch(List<WeightedItem<T>> items, int seed)
|
|
|
{
|
|
|
- int Index = Array.BinarySearch(WeightedSelector.CumulativeWeights, seed);
|
|
|
+ int index = Array.BinarySearch(WeightedSelector.CumulativeWeights, seed);
|
|
|
|
|
|
- //如果存在接近匹配项,二进制搜索返回的负数会比搜索的第1个索引少1。
|
|
|
- if (Index < 0)
|
|
|
+ //如果存在接近的匹配项,二进制搜索返回的负数会比搜索的第1个索引少1。
|
|
|
+ if (index < 0)
|
|
|
{
|
|
|
- Index = -Index - 1;
|
|
|
+ index = -index - 1;
|
|
|
}
|
|
|
|
|
|
- return items[Index];
|
|
|
+ return items[index];
|
|
|
}
|
|
|
}
|
|
|
}
|