首頁 > 軟體

利用java實現中獎概率詳情

2022-07-20 18:03:03

1. 演演算法分析

根據概率將獎品劃分割區間,每個區間代表一個獎品,然後抽取 亂數,反查落在那個區間上,即為所抽取的獎品。

2. 程式碼核心演演算法

import com.alibaba.fastjson.JSONObject;
import java.math.BigDecimal;
import java.util.*;
//抽獎核心演演算法
public class Arithmetic {
// 放大倍數
private static final int mulriple = 1000000;
public static int pay(List<Prize> prizes) {
int lastScope = 0;
// 洗牌,打亂獎品次序
Collections.shuffle(prizes);
Map prizeScopes = new HashMap();
Map prizeQuantity = new HashMap();
for (Prize prize : prizes) {
int prizeId = prize.getPrizeId();
// 劃分割區間
int currentScope = lastScope + prize.getProbability().multiply(new BigDecimal(mulriple)).intValue();
prizeScopes.put(prizeId, new int[]{lastScope + 1, currentScope});
prizeQuantity.put(prizeId, prize.getQuantity());
lastScope = currentScope;
}
// 獲取1-1000000之間的一個亂數
int luckyNumber = new Random().nextInt(mulriple);
int luckyPrizeId = 0;
// 查詢亂數所在的區間
if ((null != prizeScopes) && !prizeScopes.isEmpty()) {
Set set = prizeScopes.entrySet();
for (Object o : set) {
Map.Entry m = (Map.Entry) o;
int key = (int) m.getKey();
Object value = m.getValue();
Integer[] val = JSONObject.parseObject(JSONObject.toJSONString(value), Integer[].class);
if (luckyNumber >= val[0] && luckyNumber <=val[1] && Integer.parseInt(prizeQuantity.get(key)+"") > 0) {
luckyPrizeId = key;
break;
}
}
}
// if (luckyPrizeId > 0) {
// // 獎品庫存減一
// }
return luckyPrizeId;
}
public static void main(String[] args) {
List<Prize> prizes = new ArrayList();
Prize prize1 = new Prize();
prize1.setPrizeId(10000);
prize1.setProbability(new BigDecimal(0.01));
prize1.setQuantity(1);
prizes.add(prize1);

Prize prize2 = new Prize();
prize2.setPrizeId(10001);
prize2.setProbability(new BigDecimal(0.19));
prize2.setQuantity(10);
prizes.add(prize2);

Prize prize3 = new Prize();
prize3.setPrizeId(10);
prize3.setProbability(new BigDecimal(0.8));
prize3.setQuantity(1);
prizes.add(prize3);

int times = 1000;
int prize1GetTimes = 0;
int prize2GetTimes = 0;
int prize3GetTimes = 0;

for (int i = 0; i < times; i++) {
int pay = pay(prizes);
System.out.println("抽獎到了"+pay);
switch (pay) {
case 10000:
prize1GetTimes++;
break;
case 10001:
prize2GetTimes++;
break;
case 10:
prize3GetTimes++;
break;
}
}
System.out.println("抽獎次數" + times);
System.out.println("prize1中獎次數" + prize1GetTimes);
System.out.println("prize2中獎次數" + prize2GetTimes);
System.out.println("prize3中獎次數" + prize3GetTimes);
}
}

3. 抽獎物件

import lombok.Data;

import java.math.BigDecimal;
@Data
public class Prize {
//獎品唯一標示
private Integer prizeId;
//中獎概率
private BigDecimal probability;
//獎品數量
private Integer quantity;

}

執行結果如下:

通過1000次抽取,我們看出演演算法精度還是很高的。

到此這篇關於利用java實現中獎概率詳情的文章就介紹到這了,更多相關java中獎概率內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com