Expand a random range from 1–5 to 1–7

前端 未结 30 3193
一个人的身影
一个人的身影 2020-11-22 07:29

Given a function which produces a random integer in the range 1 to 5, write a function which produces a random integer in the range 1 to 7.

  1. What is a simple so
30条回答
  •  不知归路
    2020-11-22 08:20

    The following produces a uniform distribution on {1, 2, 3, 4, 5, 6, 7} using a random number generator producing a uniform distribution on {1, 2, 3, 4, 5}. The code is messy, but the logic is clear.

    public static int random_7(Random rg) {
        int returnValue = 0;
        while (returnValue == 0) {
            for (int i = 1; i <= 3; i++) {
                returnValue = (returnValue << 1) + SimulateFairCoin(rg);
            }
        }
        return returnValue;
    }
    
    private static int SimulateFairCoin(Random rg) {
        while (true) {
            int flipOne = random_5_mod_2(rg);
            int flipTwo = random_5_mod_2(rg);
    
            if (flipOne == 0 && flipTwo == 1) {
                return 0;
            }
            else if (flipOne == 1 && flipTwo == 0) {
                return 1;
            }
        }
    }
    
    private static int random_5_mod_2(Random rg) {
        return random_5(rg) % 2;
    }
    
    private static int random_5(Random rg) {
        return rg.Next(5) + 1;
    }    
    

提交回复
热议问题