题目
已有函数f() 能产生1-5的等概率随机数,那么请基于f函数编写新函数能等概率生成1-7的数字。
/**
* 请利用已有函数f()等概率产生1~7的数字
*/
public class RandomFunc {
/**
* 已有函数,等概率生成1~5的随机数
* 题目提供
*
* @return
*/
public static int f() {
return (int) (Math.random() * 5) + 1;
}
}
解题思路
- 构建0,1发生器。
- 利用0,1发生器构建2进制来表示数字;如题最大为1~7 那么 2的0次幂到 2 的 2次幂 即可表示 0~7的范围。
/**
* 请利用已有函数f()等概率产生1~7的数字
*/
public class RandomFunc {
/**
* 已有函数,等概率生成1~5的随机数
* 题目提供
*
* @return
*/
public static int f() {
return (int) (Math.random() * 5) + 1;
}
/******************答题部分*********************/
/**
* 基于f()构建0,1发生器
*
* @return
*/
public static int f1() {
int a;
do {
a = f();
} while (a == 3);
return a > 3 ? 1 : 0;
}
/**
* 基于0,1发生器构建三位的2进制数,可表示0~7的数
* @return
*/
public static int f2(){
return (f1() << 2) + (f1() << 1) + f1();
}
/**
* 基于f2()的0~7 遇0重新计算,最终得到1~7的数
* @return
*/
public static int f3(){
int a;
do {
a = f2();
}while (a==0);
return a;
}
/**
* 测试
*/
public static void main(String[] args) {
int size = 8;
int[] count = new int[size];
for (int i = 1; i < 10_000_000L; i++) {
count[f3()]++;
}
for (int i = 0; i < size; i++) {
System.out.println("出现" + i + "的次数为:" + count[i]);
}
}
}
测试输出
出现1的次数为:1429091
出现2的次数为:1429902
出现3的次数为:1427204
出现4的次数为:1426427
出现5的次数为:1429638
出现6的次数为:1429043
出现7的次数为:1428694