Cracking the coding interview--Q20.3
来源:互联网 发布:我的世界如何查看端口 编辑:程序博客网 时间:2024/06/06 08:30
题目
原文:
Write a method to randomly generate a set of m integers from an array of size n. Each element must have equal probability of being chosen.
译文:
写一个方法从n个整数的数组中产生m个随机数,要求每个数出现的概率一样。
解答
这一题和上一题洗牌程序有点相似,只需要随机选取1个元素, 然后在剩下的元素里面随机选取下一个元素,不断这样操作即可。
这样做能保证每个元素选中的概率一样吗?也就是选中每个元素的概率都是1/n? 答案是YES,让我们来做一下简单的计算。
选第1个元素:在n个中随机选,因此概率为1/n
选第2个元素:在剩下的n-1个中随机选:1/(n-1),由于第1次没有选中它, 而是在另外n-1个中选:(n-1)/n,因此概率为:(n-1)/n * 1/(n-1) = 1/n
选第3个元素:同上:(n-1)/n * (n-2)/(n-1) * 1/(n-2) = 1/n
……
因此,按照这种方法选取k个元素,每个元素都是以1/n的概率被选出来的。代码如下: 选出的m个数放到数组前m个位置。
代码如下:
import java.util.Random;class Q20_3{public static void main(String[] args){int n=9,m=5;int[] a={1,2,3,4,5,6,7,8,9};pickMRandomly(a,n,m);for(int i=0;i<m;i++){System.out.print(a[i]+" ");}}public static void swap(int[] a,int i,int j){int t=a[i];a[i]=a[j];a[j]=t;}public static void pickMRandomly(int[] a,int n,int m){Random random = new Random();for(int i=0;i<m;++i){int j=random.nextInt(n-1)%(n-1-i+1) + i;swap(a,i,j);}}}
---EOF---
0 0
- Cracking the coding interview--Q20.3
- Cracking the coding interview--Q20.12
- Cracking the coding interview--Q20.1
- Cracking the coding interview--Q20.2
- Cracking the coding interview--Q20.4
- Cracking the coding interview--Q20.5
- Cracking the coding interview--Q20.6
- Cracking the coding interview--Q20.7
- Cracking the coding interview--Q20.8
- Cracking the coding interview--Q20.9
- Cracking the coding interview--Q20.10
- Cracking the coding interview--Q20.11
- Cracking the coding interview--Q20.12
- Cracking the coding interview--Q20.13
- Cracking the Coding Interview
- 《Cracking the coding interview》
- Cracking The Coding Interview
- Cracking the coding interview
- Python 学习入门(20)—— 循环
- 华中科技大学_2006保研___考研计算机_复试上机
- 匿名对象
- 多浏览器中实现超出部分自动换行
- request和response的知识
- Cracking the coding interview--Q20.3
- Hessian基本篇
- 关于Python
- 第7周作业1-循环大战
- 提升tomcat服务器性能的七条经验
- ftrapv编译选项会影响性能
- android的消息处理机制(图+源码分析)——Looper,Handler,Message
- 升级Ubuntu 12.04下的gcc到4.7
- 设计模式——装饰模式