数据结构-蓄水池算法

假设有一个源源不断吐出不同球的机器,只有装下10个球的袋子,每一个吐出的球,要么放入袋子,要么永远丢掉。如何做到机器吐出的每一个球之后,所有吐出的的球都等概率放入袋子中。

java 复制代码
public class Reservoir {

    public static class RandomBox{
        private int[] bag;
        private int N;
        private int count;

        public RandomBox(int capacity){
            bag = new int[capacity];
            this.N = capacity;  //  袋子容量
            count = 0;
        }

        private int rand(int max){
            return (int)(Math.random()*max) + 1; // 返回1-max之间的随机数
        }

        public void add(int num){
            count++;
            if(count<=N){
                bag[count-1] = num;
            }else{
                if(rand(num) <= N){
                    bag[rand(N)-1] = num;
                }
            }
        }

        public int[] choices(){
            int[] ans = new int[N];
            for (int i = 0; i < N; i++) {
                ans[i] = bag[i];
            }
            return ans;
        }
    }

    public static void main(String[] args) {
        int all = 100; // 一共100个数
        int choose = 10; // 选择10个放入袋子中
        int testTimes = 50000; // 测试50000次
        int[] counts = new int[all + 1];
        for (int i = 0; i < testTimes; i++) {
            RandomBox box = new RandomBox(choose);
            for (int j = 1; j <= all; j++) {
                box.add(j);
            }

            int[] ans = box.choices();
            for (int j = 0; j < ans.length; j++) {
                counts[ans[j]]++;
            }
        }

        for (int i = 0; i < counts.length; i++) {
            System.out.println(i+" times: "+counts[i]);
        }
    }

}
相关推荐
夏末秋也凉9 小时前
力扣-回溯-46 全排列
数据结构·算法·leetcode
王老师青少年编程9 小时前
【GESP C++八级考试考点详细解读】
数据结构·c++·算法·gesp·csp·信奥赛
liuyuzhongcc12 小时前
List 接口中的 sort 和 forEach 方法
java·数据结构·python·list
计算机小白一个13 小时前
蓝桥杯 Java B 组之背包问题、最长递增子序列(LIS)
java·数据结构·蓝桥杯
卑微的小鬼14 小时前
数据库使用B+树的原因
数据结构·b树
cookies_s_s14 小时前
Linux--进程(进程虚拟地址空间、页表、进程控制、实现简易shell)
linux·运维·服务器·数据结构·c++·算法·哈希算法
醉城夜风~16 小时前
[数据结构]双链表详解
数据结构
gyeolhada16 小时前
2025蓝桥杯JAVA编程题练习Day5
java·数据结构·算法·蓝桥杯
阿巴~阿巴~16 小时前
多源 BFS 算法详解:从原理到实现,高效解决多源最短路问题
开发语言·数据结构·c++·算法·宽度优先
刃神太酷啦18 小时前
堆和priority_queue
数据结构·c++·蓝桥杯c++组