@[TOC]算法学习笔记
1.等概率返回[0,1)之间的数。如x属于[0,1),在[0,x)之间的出现的概率为x
Math.Random();
2.x属于[0,1),在[0,x)之间的出现的概率为x^2
Math.max(Math.Random(),Math.Random());
3.返回1-5的随机整数
public int f1(){
return (int)(Math.random()*5 + 1);
}
4.假设只有可以返回1、2、3、4、5五个数的函数f1(),设计一个等概率01发生器
public int f2(){
int ans = 0;
do{
ans = f();
}while(ans == 3);//如果是1,2,返回0,如果是4,5返回1,如果是3,继续循环
return ans < 3 ? 0 : 1;
}
5.假设只有f2(),等概率返回0-7之间的数。0-7的二进制位有三位,000-111
public int f3(){
return (f2()<<2 + f2()<<1 + f2());
}
6.仅使用f3(),返回0-6等概率的数
public int f4(){
int ans = 0;
do{
ans = f4();
}while(ans == 7); //出现7就重做,否则返回
return ans;
}
7.存在一个可以等概率返回3-19之间的数的方法f5,求等概率返回17-56之间的一个数
3-19可以做成0、1发生器,3-10返回0,12-19返回1,11返回重做
17-56相当于0-39等概率,再加上17。39可以使用6个二进制位表示,所以使用0、1发生器六次
public int f6(){
int ans = 0;
do{
ans = f5()<<5 + f5()<<4 + f5()<<3 + f5()<<2 + f5()<<1 + f5();
}while(ans > 39); //大于39 就重做
return ans + 17;
}
8.存在一个方法f不等概率返回0或1,0为p,1为1-p,求一个等概率返回0、1的方法
做两次,产生01或10,概率是p*(1-p);
public int f7(){
int ans = 0;
do{
ans = f();
}while(ans == f()); //外层调用一次f(),如果两次的结果相同,重做,不同返回
return ans;