Java抽奖概率算法
生活随笔
收集整理的這篇文章主要介紹了
Java抽奖概率算法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 獎品
- 實體
- 抽獎方法
- 測試
- 感謝
獎品
實體
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();// 計算總概率,這樣可以保證不一定總概率是1double 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);} }
結果與預期差不多。
感謝
- https://yq.aliyun.com/articles/44578/
總結
以上是生活随笔為你收集整理的Java抽奖概率算法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 十分钟掌握Nodejs下载和安装
- 下一篇: mergesort java_排序--归