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

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

    As long as there aren't seven possibilities left to choose from, draw another random number, which multiplies the number of possibilities by five. In Perl:

    $num = 0;
    $possibilities = 1;
    
    sub rand7
    {
      while( $possibilities < 7 )
      {
        $num = $num * 5 + int(rand(5));
        $possibilities *= 5;
      }
      my $result = $num % 7;
      $num = int( $num / 7 );
      $possibilities /= 7;
      return $result;
    }
    

提交回复
热议问题