欢迎关注Github:https://github.com/teaey/
权重随机在项目中经常用到,所以我把它抽象到一个工具类中。
public abstract class WeightRandom<T> {
public static <T> WeightRandom<T> build(Map<T, Integer> map, Class<? extends WeightRandom> implClazz) {
if (!WeightRandom.class.isAssignableFrom(implClazz)) {
throw new IllegalArgumentException("implClass");
}
try {
Constructor<? extends WeightRandom> constructor = implClazz.getConstructor(Map.class);
WeightRandom weightRandom = constructor.newInstance(map);
weightRandom.init();
return weightRandom;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected final Map<T, Integer> data;
protected volatile Random ran;
publi

这篇博客介绍了在项目中实现权重随机的三种方法:1)通过数组存储目标和权重;2)利用二分搜索算法和权重累加;3)使用二叉树结构。每种方法都有其优缺点,例如数组实现简单但可能浪费内存,二分搜索算法节省内存但实现相对复杂。
最低0.47元/天 解锁文章
5887

被折叠的 条评论
为什么被折叠?



