数组的常用算法(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对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树
- [原创]java局域网聊天系统