問題:dom
給定一隨機函數f,等機率返回1-5中的一個數字,這是你惟一可以使用的隨機機制(不可調用其餘隨機方法),如何實現等機率返回1-7中的數字?函數
解題思路:spa
既然只能使用已給定的隨機方法,那麼咱們能如何處理呢?code
首先咱們要想到二進制,由於二進制能夠表示任意十進制數。即0000 0001表示1,0000 0100表示4。至此咱們發現只要有一個函數返回0/1等機率。blog
那麼使用二進制位運算就能夠表示任意十進制數。
class
//等機率返回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]); } }