果壳科学人有一篇文章《为了集齐108将,你得吃多少袋干脆面》 http://www.guokr.com/article/5583/
讨论了一个有趣的概率问题,也是离散概率里非常经典的Coupon Collector Problem.
这个问题同时引发了想要用java整理数组常用算法的兴趣,那么就从集齐108将开始。
(一)集优惠券
方便面公司印了108种不同的券, 每袋方便面里每种券出现的概率是均等的,那你手头总共有多少张券的时候,才能包含108种?
思考过程:
很自然地先想到用一个N(N=108) 个元素的数组,将0到N-1随机排列。每一个数值代表了一种券。
对每一种券,我们需要知道的是:是否已经收集到。这是一个切换思路的关键点,即可以用一个boolean的数组found[], 利用券的数值作为数组脚标--如果数值i代表的券已经收集过,则 found[i]为真,否则为假。
需要记录两个值:1)收到了多少种不同的券,2)收集了多少张券
public class CouponCollector {
public static void main(String[] args) {
int N = 108; // 108 different heroes
boolean[] found = new boolean[N];
int totalNum = 0; // total cards collected
int distinctNum = 0; //different heroes collected
while(distinctNum < N) {
int card = (int) (Math.random() * N); //randomly collect one card
totalNum++;
if(!found[card]) {
distinctNum++;
found[card] = true;
}
} // keep collecting until N different heroes found
System.out.printf("You have collected %d cards to get %d heroes", totalNum, N);
System.out.println();
}
}