import java.math.BigDecimal;
import java.util.*;
/**
* @author 22052
*/
public class ProbabilityUtil {
/**
* 按照概率进行抽奖
* @param probabilityRecordList
* @return
*/
public static String getByProbability(List<ProbabilityRecord> probabilityRecordList){
Random random = new Random();
double randomProbability = random.nextDouble();
double cumulativeProbability = 0.0;
for (ProbabilityRecord record : probabilityRecordList) {
if (randomProbability < (cumulativeProbability += (record.probability().doubleValue()/100.0))) {
return record.code();
}
}
return "";
}
public static void main(String[] args) {
ProbabilityRecord record = new ProbabilityRecord("1",new BigDecimal("1"));
ProbabilityRecord record2 = new ProbabilityRecord("2",new BigDecimal("1"));
ProbabilityRecord record3 = new ProbabilityRecord("3",new BigDecimal("1"));
ProbabilityRecord record4 = new ProbabilityRecord("4",new BigDecimal("1"));
ProbabilityRecord record5 = new ProbabilityRecord("5",new BigDecimal("46"));
ProbabilityRecord record6 = new ProbabilityRecord("6",new BigDecimal("50"));
Map<String,Integer> map = new HashMap<>();
for(var i = 0 ; i < 60 ; i++){
String byProbability = getByProbability(List.of(record, record2, record3, record4, record5, record6));
Integer integer = map.get(byProbability);
if(Objects.isNull(integer)){
map.put(byProbability,1);
}else{
map.put(byProbability,integer+1);
}
}
System.out.println(map);
}
}
转盘抽奖算法
于 2023-12-11 11:17:58 首次发布