算法 等概率问题

问题:

  给定一随机函数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.cnblogs.com/unknown6248/p/14577791.html