算法第四版1.4算法分析:习题1.4.45

本文通过编程实现并探讨了优惠券收集问题,即在一系列独立且等概率的随机选择中,平均需要多少次尝试才能收集到所有类型的优惠券。通过多次实验,计算了平均值并对比了数学期望。

题目是所有的数都生成的前一次的生成数用了多少次

import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;

public class E1_4_45 {
    public static void main(String[]args){
        int N=50000;
        double sum=0.0;
        for (int i=0;i<5000;i++){//
            int temp=CouponCollectorProblem(N);
            sum+=temp;
            StdOut.printf("N=%8d  find=%8d\n",N,temp);
        }
        StdOut.println("avg="+sum/5000+"  expectation="+Math.sqrt(Math.PI*N/2));
    }

    public static int CouponCollectorProblem(int N){
        int total=0;
        boolean[]res=new boolean[N];//默认是false
        int cnt=0;//用来存放已经生成多少个不重复的数,这样就不用遍历数组了
        int prev= StdRandom.uniform(0,N);total++;
        res[prev]=true;cnt++;
        int now=StdRandom.uniform(0,N);total++;
        if (!res[now]){//res[now]==false
            res[now]=true;
            cnt++;
        }
        while (cnt<N){
            prev=now;
            now=StdRandom.uniform(0,N);total++;
            if (!res[now]){//res[now]==false
                res[now]=true;
                cnt++;
            }
        }
        return total;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值