数据结构-蓄水池算法

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

}
相关推荐
雪落漂泊6 小时前
C++算法:双指针篇(下)
数据结构·c++·算法
学逆向的16 小时前
C 循环结构的执行效率分析
c语言·开发语言·数据结构·网络安全
jeo陽20 小时前
04-循环实战:素数、最大公约数、级数求和与枚举法
c语言·开发语言·数据结构
slandarer21 小时前
MATLAB | 趣味编程——动态字符串甜甜圈和爱心
数据结构·matlab·趣味编程
UIU11421 小时前
P1003 [NOIP 2011 提高组] 铺地毯
数据结构·c++·算法
爱读书的小胖1 天前
LeetCode 88. 合并两个有序数组 C 解题分析
c语言·数据结构·算法
inrichtt1 天前
第七课时:STM32时钟系统揭秘:从零理解时钟树
c语言·数据结构·stm32·单片机·嵌入式硬件
xxwl5851 天前
区域赛算法模版第四章---数据结构
数据结构·c++·算法
Logic1011 天前
C语言/数据结构二维数组题解:找出行列O个数均为偶数的格子——奇偶性预处理+二次遍历
c语言·数据结构·算法·二维数组·时间复杂度·动态内存分配·奇偶性
垆边人似月.1 天前
移动长度 k 子串使字符串变成回文
数据结构·算法