問題:
給定一隨機函式f,等概率回傳1-5中的一個數字,這是你唯一可使用的隨機機制(不可呼叫其他隨機方法),如何實作等概率回傳1-7中的數字?
解題思路:
既然只能使用已給定的隨機方法,那么我們能如何處理呢?
首先我們要想到二進制,因為二進制可以表示任意十進制數,即0000 0001表示1,0000 0100表示4,至此我們發現只要有一個函式回傳0/1等概率,
那么使用二進制位運算就可以表示任意十進制數,
//等概率回傳1-5
public static int f()
{
return (int)(Math.random() * 5) + 1;
}
//等概率回傳0/1
public static int a()
{
int i = 0;
do {
i = f();
}while(i == 3);
return i < 3 ? 0 : 1;
}
//等概率回傳1-7也就是0-6
public static int b() {
int i = 0;
do {
i = (a() << 2) + (a() << 1) + a();
}while(i == 7);
return i;
}
public static void main(String[] args){
int[] count = new int[8];
int j = 0;
for (int i =0; i<40000000; i++) {
count[b()] ++ ;
}
for (int i=0;i<count.length;i++) {
System.out.println(i + ": " + count[i]);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/270766.html
標籤:其他
上一篇:Schemer遞回
下一篇:演算法 蓄水問題
