獎品
實體
package com.leigq.www.shiro.controller;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
/**
* 獎品 DTO
* <br/>
*
* @author :leigq
* @date :2019/7/5 23:00
*/
@Data
@Builder
@AllArgsConstructor
public class GiftDTO {
/**
* 索引
*/
private Integer index;
/**
* 獎品名稱
*/
private String name;
/**
* 獎品編號
*/
private String no;
/**
* 中獎概率
*/
private Double probability;
}
抽獎方法
/**
* 抽獎方法
* <br/>
* create by: leigq
* <br/>
* create time: 2019/7/5 23:08
* @param orignalRates 商品中獎概率列表,保證順序和實際物品對應
* @return 中獎商品索引
*/
public static int lottery(List<Double> orignalRates) {
if (orignalRates == null || orignalRates.isEmpty()) {
return -1;
}
int size = orignalRates.size();
// 計算總概率,這樣可以保證不一定總概率是1
double sumRate = 0d;
for (double rate : orignalRates) {
sumRate += rate;
}
// 計算每個物品在總概率的基礎下的概率情況
List<Double> sortOrignalRates = new ArrayList<>(size);
Double tempSumRate = 0d;
for (double rate : orignalRates) {
tempSumRate += rate;
sortOrignalRates.add(tempSumRate / sumRate);
}
// 根據區塊值來獲取抽取到的物品索引
double nextDouble = Math.random();
sortOrignalRates.add(nextDouble);
Collections.sort(sortOrignalRates);
return sortOrignalRates.indexOf(nextDouble);
}
測試
我這裏就只用兩個商品測試
public static void main(String[] args) {
List<GiftDTO> gifts = new ArrayList<>();
gifts.add(new GiftDTO(1, "一等獎", "P1", 0.4d));
gifts.add(new GiftDTO(2, "謝謝參與","P2", 0.6d));
// 存儲概率
List<Double> orignalRates = new ArrayList<>(gifts.size());
for (GiftDTO gift : gifts) {
double probability = gift.getProbability();
if (probability < 0) {
probability = 0;
}
orignalRates.add(probability);
}
// 統計
Map<Integer, Integer> count = new HashMap<>();
// 測試次數
double num = 1000000;
for (int i = 0; i < num; i++) {
int orignalIndex = lottery(orignalRates);
Integer value = count.get(orignalIndex);
count.put(orignalIndex, value == null ? 1 : value + 1);
}
for (Map.Entry<Integer, Integer> entry : count.entrySet()) {
System.out.println(gifts.get(entry.getKey()) + ", 命中次數=" + entry.getValue() + ", 實際概率="
+ entry.getValue() / num);
}
}
結果與預期差不多。