奖品对象
public class PrizeEntity {
//奖品id
private Integer id;
//奖品总数
private Integer prizeCount;
//中奖概率
private Double Probability;
//奖品名称
private String prizeName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getPrizeCount() {
return prizeCount;
}
public void setPrizeCount(Integer prizeCount) {
this.prizeCount = prizeCount;
}
public Double getProbability() {
return Probability;
}
public void setProbability(Double probability) {
Probability = probability;
}
public String getPrizeName() {
return prizeName;
}
public void setPrizeName(String prizeName) {
this.prizeName = prizeName;
}
}
抽奖工具类
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class LotteryTool {
private Map<PrizeEntity, Double> prizes; // 存储奖品及其概率
private Map<PrizeEntity, Integer> prizeCounts; // 存储奖品及其数量
private double totalProbability; // 总概率
public LotteryTool() {
prizes = new HashMap<>();
prizeCounts = new HashMap<>();
totalProbability = 0.0;
}
// 添加奖品及其概率
public void addPrize(PrizeEntity prize) {
prizes.put(prize, prize.getProbability());
prizeCounts.put(prize, prize.getPrizeCount());
totalProbability += prize.getProbability();
}
// 进行抽奖,允许总概率不为1
public PrizeEntity draw() {
Random random = new Random();
double randomNumber = random.nextDouble() * totalProbability;
double cumulativeProbability = 0.0;
for (Map.Entry<PrizeEntity, Double> entry : prizes.entrySet()) {
PrizeEntity prize = entry.getKey();
double probability = entry.getValue();
int count = prizeCounts.get(prize);
if (count > 0) { // 奖品数量大于0时才进行抽取
cumulativeProbability += probability;
if (randomNumber < cumulativeProbability) {
prizeCounts.put(prize, count - 1); // 减少奖品数量
return prize;
}
}
}
return null;
}
public static void main(String[] args) {
LotteryTool lotteryTool = new LotteryTool();
PrizeEntity prize1=new PrizeEntity();
prize1.setId(1);
prize1.setPrizeCount(1);
prize1.setPrizeName("一等奖");
prize1.setProbability(0.1);
PrizeEntity prize2=new PrizeEntity();
prize2.setId(2);
prize2.setPrizeCount(1);
prize2.setPrizeName("二等奖");
prize2.setProbability(0.2);
lotteryTool.addPrize(prize2);
PrizeEntity prize3=new PrizeEntity();
prize3.setId(3);
prize3.setPrizeCount(2);
prize3.setPrizeName("三等奖");
prize3.setProbability(0.3);
lotteryTool.addPrize(prize3);
for (int i = 0; i < 20; i++) {
PrizeEntity entity=lotteryTool.draw();
if(entity!=null){
System.out.println("抽奖结果:" +entity.getPrizeName());
}else {
System.out.println("抽奖结果:未中奖");
}
}
}
}