關於抽獎的概率演算法
@Test
public void test(){
//0表示謝謝參與
int index = 0;
//------獎品-------
Map<Integer, String> map = new HashMap<>();
map.put(0, "謝謝參與");
map.put(1, "一等獎");
map.put(2, "二等獎");
map.put(3, "三等獎");
map.put(4, "四等獎");
//------獎品對應的概率-------
List<Double> orignalRates = new ArrayList<Double>();
orignalRates.add(0.1);//謝謝參與
orignalRates.add(0.2);//一等獎
orignalRates.add(0.3);//二等獎
orignalRates.add(0.3);//三等獎
orignalRates.add(0.1);//四等獎
Map<Integer, Integer> count = new HashMap<Integer, Integer>();
double num = orignalRates.size();
//計算隨機數落在每個區間的次數
for (int i = 0; i < num; i++) {
int orignalIndex = lottery(orignalRates);
Integer value = count.get(orignalIndex);
count.put(orignalIndex, value == null ? 1 : value + 1);
}
System.out.println("============"+count);
Collection<Integer> countValue = count.values();
Object[] valueArray = countValue.toArray();
Arrays.sort(valueArray);
Integer maxValue = (Integer) valueArray[valueArray.length - 1];
for (Integer key : count.keySet()) {
Integer value = count.get(key);
if (value == maxValue) {
index = key;
break;
}
}
System.out.println("============"+map.get(index));
}
public static int lottery(List<Double> rates) {
if (rates == null || rates.isEmpty()) {
return -1;
}
// 計算總概率
double sumRate = 0d;
for (double rate : rates) {
sumRate += rate;
}
// 計算每個物品的概率
List<Double> sortRates = new ArrayList<Double>();
Double tempSumRate = 0d;
for (double rate : rates) {
tempSumRate += rate;
sortRates.add(tempSumRate / sumRate);
}
//用 Math.random()獲取0-1之間的一個隨機數,並放入集合中
double nextDouble = Math.random();
sortRates.add(nextDouble);
//集合重新排序
Collections.sort(sortRates);
//獲取隨機數索引,也就是隨機數所在的區間
int i = sortRates.indexOf(nextDouble);
return i;
}