Cracking the coding interview--Q20.3
2014-04-21 09:41
218 查看
题目
原文:
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---
原文:
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---
相关文章推荐
- Cracking the coding interview--Q15.4
- cracking the coding interview No1.2
- cracking the coding interview No1.8
- Cracking the coding interview--Q1.1
- Cracking The Coding Interview 1.6
- Cracking the coding interview的习题解答
- Cracking the Coding Interview 150题(一)
- Cracking the Coding Interview 之测试
- 【Cracking the coding interview】Q1.3(移除重复字符)
- Cracking the Coding Interview:: 寻找有环链表的环路起始节点
- 《Cracking the Coding Interview》——第10章:可扩展性和存储空间限制——题目2
- 《Cracking the Coding Interview》——第12章:测试——题目3
- Cracking the Coding Interview Q3.1
- 《Cracking the Coding Interview》——第17章:普通题——题目7
- 《Cracking the Coding Interview》——第18章:难题——题目5
- Cracking The Coding Interview 3rd -- 1.2
- Cracking the coding interview--Q8.4
- Cracking the coding interview--Q9.4
- Cracking the coding interview--Q1.7
- Cracking the coding interview--Q2.1