数据结构-蓄水池算法

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

}
相关推荐
楼田莉子15 分钟前
C++算法题目分享:二叉搜索树相关的习题
数据结构·c++·学习·算法·leetcode·面试
小明的小名叫小明1 小时前
区块链技术原理(14)-以太坊数据结构
数据结构·区块链
pusue_the_sun1 小时前
数据结构——栈和队列oj练习
c语言·数据结构·算法··队列
奶黄小甜包2 小时前
C语言零基础第18讲:自定义类型—结构体
c语言·数据结构·笔记·学习
想不明白的过度思考者2 小时前
数据结构(排序篇)——七大排序算法奇幻之旅:从扑克牌到百亿数据的魔法整理术
数据结构·算法·排序算法
一支闲人2 小时前
C语言相关简单数据结构:双向链表
c语言·数据结构·链表·基础知识·适用于新手小白
姜不吃葱2 小时前
【力扣热题100】双指针—— 接雨水
数据结构·算法·leetcode·力扣热题100
拂晓银砾3 小时前
Java数据结构-队列
java·数据结构
John.Lewis3 小时前
数据结构初阶(19)外排序·文件归并排序的实现
c语言·数据结构·排序算法
John.Lewis3 小时前
数据结构初阶(16)排序算法——归并排序
c语言·数据结构·排序算法