Java實現隨機抽取獎品工具類
阿新 • • 發佈:2019-02-18
隨機抽取獎品
獎品 | 抽取概率 |
---|---|
10000元 | 90% |
28888元 | 4% |
66666元 | 3% |
88888元 | 2% |
100000元 | 1% |
整體思路:
- 獎品集合 + 概率比例集合
- 將獎品按集合中的順序概率計算成所佔比例區間,放入比例集合。併產生一個隨機數加入其中,進行排序。
- 排序後隨機數落在那個區間就表示那個區間的獎品被抽中。
- 返回的隨機數在集合中的索引,該索引就是獎品集合的中的索引。
- 比例區間的計算通過概率相加獲得。
//獎品的實體類 public class Gift { private String id; //獎品Id private String name; //獎品名稱 private double prob; //獲獎概率 private String type; }
實現方法:
public class DrawLotteryUtil { public static int drawGift(List<Gift> giftList){ if(null != giftList && giftList.size()>0){ List<Double> orgProbList = new ArrayList<Double>(giftList.size()); for(Gift gift:giftList){ //按順序將概率新增到集合中 orgProbList.add(gift.getProb()); } return draw(orgProbList); } return -1; } public static int draw(List<Double> giftProbList){ List<Double> sortRateList = new ArrayList<Double>(); // 計算概率總和 Double sumRate = 0D; for(Double prob : giftProbList){ sumRate += prob; } if(sumRate != 0){ double rate = 0D; //概率所佔比例 for(Double prob : giftProbList){ rate += prob; // 構建一個比例區段組成的集合(避免概率和不為1) sortRateList.add(rate / sumRate); } // 隨機生成一個隨機數,並排序 double random = Math.random(); sortRateList.add(random); Collections.sort(sortRateList); // 返回該隨機數在比例集合中的索引 return sortRateList.indexOf(random); } return -1; } //測試 public static void main(String[] args) { Gift iphone = new Gift(); iphone.setName("10000元"); iphone.setProb(0.9D); Gift thanks = new Gift(); thanks.setName("28888元"); thanks.setProb(0.04D); Gift vip = new Gift(); vip.setName("66666元"); vip.setProb(0.03D); Gift vip1 = new Gift(); vip1.setName("88888元"); vip1.setProb(0.02D); Gift vip2 = new Gift(); vip2.setName("100000元"); vip2.setProb(0.01D); List<Gift> list = new ArrayList<Gift>(); list.add(vip); list.add(thanks); list.add(iphone); list.add(vip1); list.add(vip2); for(int i=0;i<20;i++){ int index = drawGift(list); System.out.println("獎品:"+list.get(index).getName()+"***抽中的概率:"+list.get(index).getProb()); } } }
測試結果:
獎品:10000元***抽中的概率:0.9
獎品:10000元***抽中的概率:0.9
獎品:10000元***抽中的概率:0.9
獎品:10000元***抽中的概率:0.9
獎品:10000元***抽中的概率:0.9
獎品:10000元***抽中的概率:0.9
獎品:66666元***抽中的概率:0.03
獎品:28888元***抽中的概率:0.04
獎品:10000元***抽中的概率:0.9
獎品:28888元***抽中的概率:0.04
獎品:10000元***抽中的概率:0.9
獎品:88888元***抽中的概率:0.02
獎品:10000元***抽中的概率:0.9
獎品:10000元***抽中的概率:0.9
獎品:10000元***抽中的概率:0.9
獎品:10000元***抽中的概率:0.9
獎品:10000元***抽中的概率:0.9
獎品:10000元***抽中的概率:0.9
獎品:10000元***抽中的概率:0.9
獎品:10000元***抽中的概率:0.9