一、Math.random()
概率P(Math.random()<0.3) = 0.3
若x∈(0,1) 则x²概率表达为
Math.min(Math.random()<x,Math.random()<x)
二、等概率转换
给出一个黑盒f()等概率返回1、2、3、4、5,根据f()写一个等概率返回123456的函数
//等概率返回0,1的函数
public static int f1() {
int res = -1;
do {
res = f();
} while (res == 3);
return res < 3 ? 0 : 1;
}
//等概率返回0-7
public static int f2() {
return (f1() << 2) + (f1() << 1) + f1();
}
//等概率返回1-6
public static int f3() {
int res = -1;
do {
res = f2();
} while (res == 0 || res == 7);
return res;
}
三、不等概率转换
给出一个黑盒f()不等概率返回0,1,根据f()写一个等概率返回0,1的函数
public static int f1(){
int res = -1;
do {
res = f();
}while (res == f());
return res;
}
四、生成一个随机数组
public static int[] randomArr(int maxLen, int maxValue) {
int len = (int) (Math.random() * maxLen);
int[] arr = new int[len];
for (int i = 0; i < len; i++) {
arr[i] = (int) (Math.random() * maxValue);
}
return arr;
}