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

前端 未结 30 3377
一个人的身影
一个人的身影 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:13

    in php

    function rand1to7() {
        do {
            $output_value = 0;
            for ($i = 0; $i < 28; $i++) {
                $output_value += rand1to5();
            }
        while ($output_value != 140);
        $output_value -= 12;
        return floor($output_value / 16);
    }
    

    loops to produce a random number between 16 and 127, divides by sixteen to create a float between 1 and 7.9375, then rounds down to get an int between 1 and 7. if I am not mistaken, there is a 16/112 chance of getting any one of the 7 outcomes.

提交回复
热议问题