数据结构-蓄水池算法

假设有一个源源不断吐出不同球的机器,只有装下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]);
        }
    }

}
相关推荐
minji...38 分钟前
数据结构 堆(4)---TOP-K问题
java·数据结构·算法
落羽的落羽2 小时前
【C++】论如何封装红黑树模拟实现set和map
数据结构·c++·学习
一百天成为python专家3 小时前
K-近邻算法
数据结构·python·算法·pandas·近邻算法·ipython·python3.11
小新学习屋3 小时前
《剑指offer》-数据结构篇-哈希表/数组/矩阵/字符串
数据结构·leetcode·哈希表
爱装代码的小瓶子13 小时前
数据结构之队列(C语言)
c语言·开发语言·数据结构
aramae16 小时前
大话数据结构之<队列>
c语言·开发语言·数据结构·算法
cccc来财17 小时前
Java实现大根堆与小根堆详解
数据结构·算法·leetcode
刚入坑的新人编程19 小时前
暑期算法训练.9
数据结构·c++·算法·leetcode·面试·排序算法
找不到、了21 小时前
Java排序算法之<选择排序>
数据结构·算法·排序算法
小徐不徐说1 天前
动态规划:从入门到精通
数据结构·c++·算法·leetcode·动态规划·代理模式