Chinaunix首页 | 论坛 | 博客
  • 博客访问: 220875
  • 博文数量: 136
  • 博客积分: 2919
  • 博客等级: 少校
  • 技术积分: 1299
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-11 09:08
文章分类

全部博文(136)

文章存档

2013年(1)

2011年(135)

我的朋友

分类: Java

2011-08-30 11:10:46

问题描述.假设某交易卡公司发行N种不同的卡,收集每种卡具有等可能概率,问收集全N种不同的卡需要购买多种张卡?

Coupon Collector Problem. Suppose that a trading card company issues trading cards with N different possible cards: how many do you have to collect before you have all N possibilities, assuming that each possibility is equally likely for each card that you collect?

  1. /***************************************************************************
  2.   * Compilation: javac CouponCollector
  3.   * Execution: java CouponCollector N
  4.   *
  5.   * Given N distinct card types, how many random cards do you need
      *  do collect before you have (at least) one of each type?
     *  This program simulates this random process.
     *   
  6.   * Sample execution:
  7.   * % java CouponCollector 30
  8.   * The number of coupons is 117
  9.   *
  10.   *
  11.   * ***************************************************************************/

  12. public class CouponCollector {
  13.     public static void main(String[] args) {
  14.         int N = Integer.parseInt(args[0]);
  15.         boolean[] found = new boolean[N];
  16.         int count = 0; // number of cards collected
  17.         int valcnt = 0; // number of distinct cards
  18.         
  19.         while (valcnt < N) {
  20.             int val = (int) (Math.random()*N);
  21.             count++;
  22.             if (!found[val]){
  23.                 valcnt++;
  24.                 found[val] = true;
  25.             }
  26.     }
  27.         System.out.println("The number of coupons is " + count);
  28.         
  29.      }
  30. }

阅读(825) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~