/**
* 根据权重获取奖励
*
* @param awardMap
* @return key:奖励 value:权重
* @param <T>
*/
public static <T> T getRandomValue(Map<T, Integer> awardMap) {
// 获取权重和
int totalWeight = awardMap.values().stream().mapToInt(Integer::intValue).sum();
// 生成一个随机数
int randomNum = new Random().nextInt(totalWeight);
int prev = 0;
for (Map.Entry<T, Integer> entry : awardMap.entrySet()) {
if (randomNum < prev + entry.getValue()) {
return entry.getKey();
}
prev += entry.getValue();
}
return null;
}
经测试,运行100w次仅耗时121毫秒!
评论 (0)