引入

给定一个方法f(),以固定概率但不是等概率返回0和1。现在要求实现方法g(),等概率返回0和1。

思路

这种题要求01不等概率随机到01等概率随机,不妨设f()返回0的概率为pp,则返回1的概率为1p1-p。其实如果看过上篇和中篇的话,应该会有点思路,其实就还是返回某些值的时候重新调用f()方法。连续调用两次f()方法,有四种返回值可能,分别是00、01、10、11,对应的概率分别是p2p^2p(1p)p(1-p)(1p)p(1-p)p(1p)2(1-p)^2。答案已经显而易见,就是当两次返回值相同的时候重新调用,其他时候正常返回。

代码实现

package com.test;

public class Test {
    /*
     实现细节不可见
     01不等概率返回
     */
    public static int f(){
        return (Math.random() < 0.8) ? 0 : 1;
    }

    // 01等概率返回
    public static int g(){
        int ans;
        do{
            ans = f();
        }while(ans == f());
        return ans;
    }

    public static void main(String[] args) {
        int[] count = new int[2];
        int testTime = 1000000;
        for(int i = 0; i < testTime; i++){
            count[g()]++;
        }
        System.out.println("数字0出现的概率为:"+(double)count[0]/(double)testTime);
        System.out.println("数字1出现的概率为:"+(double)count[1]/(double)testTime);
    }
}