抽奖逻辑算法(根据指定概率)

2023-04-22后端1 分钟215 次阅读
AI 摘要鱼粮不足,AI 今天先歇着 · 正文在下面

前言

最近公司有个新的需求,需要对某些楼栋的员工,安照他们的随机抽奖概率抽奖,一共就三个奖品,那没有奖品就不发了。

教程

下面我将写一段伪代码来模拟这块逻辑

java 复制代码
public class Lottery
    public static void main(String[] args) {
        // 员工名单和随机系数
        Map<String, Double> employees = new HashMap<>();
        Random rand = new Random();
        double totalProbability = 0.0;
        for (int i = 1; i <= 100; i++) {
            String employeeName = "employee" + i;
            double probability = rand.nextDouble() * 0.9 + 0.1; // 随机生成0.1到1之间的概率
            employees.put(employeeName, probability);
            totalProbability += probability;
        }

        // 商品列表
        List<String> prizes = new ArrayList<>();
        prizes.add("a");
        prizes.add("b");
        prizes.add("c");

        // 计算员工的中奖概率
        Map<String, Double> probabilities = new HashMap<>();
        double currentProbability = 0.0;
        for (Map.Entry<String, Double> entry : employees.entrySet()) {
            String employee = entry.getKey();
            double probability = entry.getValue() / totalProbability;
            currentProbability += probability;
            probabilities.put(employee, currentProbability);
        }

        // 中奖用户和所获得的商品
        Map<String, String> winners = new HashMap<>();

        // 抽奖过程
        while (!prizes.isEmpty() && !employees.isEmpty()) {
            // 随机选择一名员工
            String selectedEmployee = null;
            double probability = rand.nextDouble();
            for (Map.Entry<String, Double> entry : probabilities.entrySet()) {
                if (probability < entry.getValue()) {
                    selectedEmployee = entry.getKey();
                    break;
                }
            }

            // 该员工中奖
            if (selectedEmployee != null) {
                // 随机选择一件商品
                int selectedPrizeIndex = rand.nextInt(prizes.size());
                String selectedPrize = prizes.get(selectedPrizeIndex);
                // 记录中奖用户和所获得的商品
                winners.put(selectedEmployee, selectedPrize);
                // 从商品列表和员工名单中移除中奖的商品和员工
                prizes.remove(selectedPrizeIndex);
                employees.remove(selectedEmployee);
            }
        }

        // 打印中奖用户和所获得的商品
        for (Map.Entry<String, String> entry : winners.entrySet()) {
            System.out.println(entry.getKey() + "获得了" + entry.getValue());
        }
    }
}
觉得有用就点个赞,不用登录也能读

评论

0 条
登录 之后才能评论
—
还没有评论,来说第一句