问题: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]); } }