问题描述.假设某交易卡公司发行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?
- /***************************************************************************
-
* Compilation: javac CouponCollector
-
* Execution: java CouponCollector N
-
*
-
* 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.
*
-
* Sample execution:
-
* % java CouponCollector 30
-
* The number of coupons is 117
-
*
-
*
-
* ***************************************************************************/
-
-
public class CouponCollector {
-
public static void main(String[] args) {
-
int N = Integer.parseInt(args[0]);
-
boolean[] found = new boolean[N];
-
int count = 0; // number of cards collected
-
int valcnt = 0; // number of distinct cards
-
-
while (valcnt < N) {
-
int val = (int) (Math.random()*N);
-
count++;
-
if (!found[val]){
-
valcnt++;
-
found[val] = true;
-
}
-
}
-
System.out.println("The number of coupons is " + count);
-
-
}
-
}
阅读(833) | 评论(0) | 转发(0) |