Class WeightRandomSelector<T>

java.lang.Object
org.miaixz.bus.core.lang.selector.WeightRandomSelector<T>
Type Parameters:
T - 权重随机获取的对象类型
All Implemented Interfaces:
Serializable, Selector<T>

public class WeightRandomSelector<T> extends Object implements Selector<T>, Serializable
权重随机选择算法实现

平时,经常会遇到权重随机算法,从不同权重的N个元素中随机选择一个,并使得总体选择结果是按照权重分布的。如广告投放、负载均衡等。

如有4个元素A、B、C、D,权重分别为1、2、3、4,随机结果中A:B:C:D的比例要为1:2:3:4。

总体思路:累加每个元素的权重A(1)-B(3)-C(6)-D(10),则4个元素的的权重管辖区间分别为[0,1)、[1,3)、[3,6)、[6,10)。 然后随机出一个[0,10)之间的随机数。落在哪个区间,则该区间之后的元素即为按权重命中的元素。

参考博客:https://www.cnblogs.com/waterystone/p/5708063.html

Since:
Java 17+
Author:
Kimi Liu
See Also:
  • Constructor Details

    • WeightRandomSelector

      public WeightRandomSelector()
      构造
    • WeightRandomSelector

      public WeightRandomSelector(WeightObject<T> weightObj)
      构造
      Parameters:
      weightObj - 带有权重的对象
    • WeightRandomSelector

      public WeightRandomSelector(Iterable<WeightObject<T>> weightObjs)
      构造
      Parameters:
      weightObjs - 带有权重的对象
    • WeightRandomSelector

      public WeightRandomSelector(WeightObject<T>[] weightObjs)
      构造
      Parameters:
      weightObjs - 带有权重的对象
  • Method Details

    • of

      public static <T> WeightRandomSelector<T> of()
      创建权重随机获取器
      Type Parameters:
      T - 权重随机获取的对象类型
      Returns:
      WeightRandomSelector
    • add

      public WeightRandomSelector<T> add(T obj, int weight)
      增加对象
      Parameters:
      obj - 对象
      weight - 权重
      Returns:
      this
    • add

      public WeightRandomSelector<T> add(WeightObject<T> weightObj)
      增加对象权重
      Parameters:
      weightObj - 权重对象
      Returns:
      this
    • clear

      public WeightRandomSelector<T> clear()
      清空权重表
      Returns:
      this
    • select

      public T select()
      下一个随机对象
      Specified by:
      select in interface Selector<T>
      Returns:
      随机对象