您的位置:首页 > 其它

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

2017-11-16 18:32 411 查看
/**
* 奖励金(礼物)模型
* 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐