package com.sfjiayuan.ld.web.modular.pay;
import com.alibaba.fastjson.JSONObject;
import com.sfjiayuan.ld.web.modular.award.entity.LdDrawAward;
import java.math.BigDecimal;
import java.util.*;
//抽奖核心算法
public class Arithmetic {
// 放大倍数
private static final int mulriple = 1000000;
public static LdDrawAward pay(List<LdDrawAward> aWards) {
int lastScope = 0;
// 洗牌,打乱奖品次序
Collections.shuffle(aWards);
Map<String, int[]> prizeScopes = new HashMap();
Map<String, LdDrawAward> prizeQuantity = new HashMap();
for (LdDrawAward award : aWards) {
String prizeId = award.getId();
BigDecimal ratio = new BigDecimal(award.getRatio());
if ((ratio.compareTo(new BigDecimal(0))) > 0) {
// 划分区间
int currentScope = lastScope + ratio.multiply(new BigDecimal(mulriple / 100)).intValue();
prizeScopes.put(prizeId, new int[]{lastScope+1, currentScope});
prizeQuantity.put(prizeId, award);
lastScope = currentScope;
}
}
// 获取1-1000000之间的一个随机数
int luckyNumber = new Random().nextInt(mulriple)+1;
LdDrawAward luckyResult = null;
// 查找随机数所在的区间
if ((null != prizeScopes) && !prizeScopes.isEmpty()) {
Set set = prizeScopes.entrySet();
for (Object o : set) {
Map.Entry m = (Map.Entry) o;
String key = (String) m.getKey();
Object value = m.getValue();
Integer[] val = JSONObject.parseObject(JSONObject.toJSONString(value), Integer[].class);
if (luckyNumber >= val[0] && luckyNumber <= val[1]) {
luckyResult = prizeQuantity.get(key);
break;
}
}
}
if (luckyResult == null) {
// 奖品库存减一
System.out.println("-------------- " + luckyNumber);
}
return luckyResult;
}
public static void main(String[] args) {
List<LdDrawAward> prizes = new ArrayList();
LdDrawAward prize1 = new LdDrawAward();
prize1.setId("1");
prize1.setRatio("0.0001");
prize1.setName("电动车");
prizes.add(prize1);
LdDrawAward prize2 = new LdDrawAward();
prize2.setId("2");
prize2.setRatio("0.2999");
prize2.setName("电视机");
prizes.add(prize2);
LdDrawAward prize3 = new LdDrawAward();
prize3.setId("3");
prize3.setRatio("99.7");
prize3.setName("充电宝");
prizes.add(prize3);
int times = 1000000;
int prize1GetTimes = 0;
int prize2GetTimes = 0;
int prize3GetTimes = 0;
for (int i = 0; i < times; i++) {
LdDrawAward pay = pay(prizes);
System.out.println("抽奖到了" + pay);
switch (pay.getId()) {
case "1":
prize1GetTimes++;
break;
case "2":
prize2GetTimes++;
break;
case "3":
prize3GetTimes++;
break;
}
}
System.out.println("抽奖次数" + times);
System.out.println("prize1中奖次数" + prize1GetTimes);
System.out.println("prize2中奖次数" + prize2GetTimes);
System.out.println("prize3中奖次数" + prize3GetTimes);
}
}