您的位置:首页 > 编程语言 > Java开发

数组的常用算法(1)--由“为了集齐108将买多少袋干脆面”展开去

2015-07-28 20:45 435 查看
果壳科学人有一篇文章《为了集齐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 heroesboolean[] found = new boolean;int totalNum = 0; // total cards collectedint distinctNum = 0; //different heroes collectedwhile(distinctNum < N) {int card = (int) (Math.random() * N); //randomly collect one cardtotalNum++;if(!found[card]) {distinctNum++;found[card] = true;}} // keep collecting until N different heroes foundSystem.out.printf("You have collected %d cards to get %d heroes", totalNum, N);System.out.println();}}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java array algorithm