Java Spring 帶權重隨機抽取

下面的代碼是因應各項禮物的總數進行加總

再從總體中隨機抽取一份的寫法

如果想要變動抽取權重(機率) 則需要在sortedMap內增加或減少相對應項目數量

// 總體抽取樣本(禮物)
int totalWeight = 0;

// 創建Map表單NavigableMap<Integer, Integer> 再遍歷原List表單(List<GiftEntity>) 
// 插入 Key及Value 到Map表單
// 再把每項樣本(禮物)細項總額加總 至 總體之中
NavigableMap<Integer, Integer> sortedMap = new TreeMap<>();

for(GiftEntity giftEntity : giftList) {

Integer gift_amount = giftEntity.getBalance();
totalWeight += gift_amount;
Integer giftId = giftEntity.getId();

sortedMap.put(totalWeight, giftId);
}

// 從 0 至 總體最大數中 隨機抽取一個值
Random random = new Random();
Double randomDouble = random.nextDouble() * totalWeight;

// 根據抽取結果(Key) 從Map表單中找到相對於List表單的值(Value)
Integer res_GiftID = sortedMap.ceilingEntry(randomDouble.intValue()).getValue();

// 創建新的Map表單再加入將最終抽取結果
Map<String, Integer>  resultMap = new HashMap<>();
resultMap.put("giftID", res_GiftID);

如有任何疑問歡迎下方留言, 希望看完的碼友們點讚支持

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值