数据结构-蓄水池算法

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

}
相关推荐
在下雨5993 分钟前
项目讲解1
开发语言·数据结构·c++·算法·单例模式
今后12316 分钟前
【数据结构】栈详解
数据结构·
songx_993 小时前
leetcode10(跳跃游戏 II)
数据结构·算法·leetcode
先做个垃圾出来………4 小时前
差分数组(Difference Array)
java·数据结构·算法
dragoooon345 小时前
[数据结构——lesson5.1链表的应用]
数据结构·链表
神里流~霜灭7 小时前
(C++)数据结构初阶(顺序表的实现)
linux·c语言·数据结构·c++·算法·顺序表·单链表
要开心吖ZSH8 小时前
软件设计师备考-(十六)数据结构及算法应用(重要)
java·数据结构·算法·软考·软件设计师
zhong liu bin9 小时前
MySQL数据库面试题整理
数据结构·数据库·mysql
bkspiderx19 小时前
C++经典的数据结构与算法之经典算法思想:贪心算法(Greedy)
数据结构·c++·算法·贪心算法
中华小当家呐20 小时前
算法之常见八大排序
数据结构·算法·排序算法