基本思路
1、确定你要的奖项,比如:一等奖、二等奖、三等奖、谢谢惠顾;
2、设置4个区间,0~5是一等奖、6~15是二等奖、16~40是三等奖、剩下的40~100是谢谢惠顾;
3、产生一个随机数,判断随机数在哪个区间之内,就会获得相应的奖项;
很简单的一个方法,刚好正在做的微信小程序这边有积分抽奖这个功能,就先写一个玩一玩,下面贴代码,因为很简单,所以后面我就不多逼逼了,大家自己看,如果有错误,欢迎指正!!
1 public JsonResult luckyDraw() {
2 JsonResult jsonResult=new JsonResult("200");
3 jsonResult.setFlag(true);
4 jsonResult.setMsg("抽奖成功");
5
6 //定义中奖率分母百分之
7 int probabilityCount=100;
8
9 //最小概率
10 String min="min";
11
12 //最大概率
13 String max="max";
14 Integer tempInt=0;
15
16 //待中将商品数组
17 Map<String,Map<String,Integer>> prizeMap=new HashMap<>();
18
19 //获取商品列表
20 List<Prize> prizeList=prizeDao.findAll();
21
22 for(Prize prize:prizeList) {
23 Map<String, Integer> oddMap=new HashMap<>();
24 //最小概率值
25 oddMap.put(min, tempInt);
26 tempInt=tempInt+prize.getPrizeOdd();
27 //最大概率
28 oddMap.put(max, tempInt);
29 prizeMap.put(prize.getId(), oddMap);//(奖品id,最小概率~最大概率)
30 }
31
32 //随机一个数字
33 int index=(int) (Math.random()* probabilityCount);
34 Prize prize=null;//中奖商品容器
35 Set<String> prizeIds=prizeMap.keySet();//拿到所有奖品id
36 for(String prizesId:prizeIds) {
37 Map<String, Integer> oddMap=prizeMap.get(prizesId);//商品的概率
38 Integer minNum=oddMap.get(min);
39 Integer maxNum=oddMap.get(max);
40
41 //校验index在那个商品概率中间
42 if(minNum <=index && maxNum > index) {
43 prize=prizeDao.getOne(prizesId);
44 break;
45 }
46 }
47
48 if(prize == null) {
49 prize=null;
50 }
51
52 jsonResult.setObj(prize.getPrizeName());
53 return jsonResult;
54 }
测试结果如下:

