随机获取礼物活动总结(抽奖算法)

来源:互联网 发布:膛线无缝管淘宝有售吗 编辑:程序博客网 时间:2024/05/22 17:51
/** * 奖励金(礼物)模型 * Created by tong.hua on 2017-10-26. */public class BountyItem extends ToString{    private static final long serialVersionUID = -4046365922597449030L;    //礼物编号    private int giftId;    //礼物类型 cash 现金  deduction 抵扣红包 coupon 加息券    private String giftType;    //礼物编号    private String poolNo;    //礼物名称    private String name;    //中奖几率    private String probability;    public int getGiftId() {        return giftId;    }    public void setGiftId(int giftId) {        this.giftId = giftId;    }    public String getGiftType() {        return giftType;    }    public void setGiftType(String giftType) {        this.giftType = giftType;    }    public String getPoolNo() {        return poolNo;    }    public void setPoolNo(String poolNo) {        this.poolNo = poolNo;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getProbability() {        return probability;    }    public void setProbability(String probability) {        this.probability = probability;    }}


核心算法

/**     * 根据概率获取礼物集合中的礼物     * @param bountyItems 礼物列表     * @return     * 1.把礼物id,礼物的概率放大10000倍,存入map集合中 <giftid,[currentScope,lastScope]>     *     <1,[1-500]>  <2,[500-1500]>  <3,[1500-3000]>     * 2.获取1-10000之间的一个随机数(幸运数)luckyNumber  比如:1700     * 3.遍历map,找出1700所在的区间,获取幸运id,luckyItemId 3     * 4.根据luckyItemId,取出bountyItems中对应的礼物     *     */    private BountyItem getBountyItem(List<BountyItem> bountyItems) {        // 放大倍数        int mulriple = 10000;        int lastScope = 0;        // 洗牌,打乱奖品次序        Collections.shuffle(bountyItems);        Map<Integer, int[]> itemScopes = new HashMap<Integer, int[]>();        for (BountyItem item : bountyItems) {            int giftId = item.getGiftId();            // 划分区间            int currentScope = lastScope + new BigDecimal(item.getProbability()).multiply(new BigDecimal(mulriple)).intValue();            itemScopes.put(giftId, new int[] { lastScope + 1, currentScope });            lastScope = currentScope;        }        // 获取1-10000之间的一个随机数        int luckyNumber = new Random().nextInt(mulriple);        int luckyItemId = 0;        // 查找随机数所在的区间        if (!itemScopes.isEmpty()) {            Set<Map.Entry<Integer, int[]>> entrySets = itemScopes.entrySet();            for (Map.Entry<Integer, int[]> m : entrySets) {                int key = m.getKey();                if (luckyNumber >= m.getValue()[0] && luckyNumber <= m.getValue()[1]) {                    luckyItemId = key;                    break;                }            }        }        //根据luckyItemId从礼物集合中选中礼物        BountyItem selectedItem = new BountyItem();        for(BountyItem item : bountyItems){            int giftId = item.getGiftId();            if(giftId == luckyItemId){                selectedItem = item;            }        }        return selectedItem;    }