首页 > 其他 > 详细

rand(5) -> rand(7)

时间:2014-10-07 06:01:13      阅读:321      评论:0      收藏:0      [点我收藏+]
int rand7() //random number from 1 - 7
{
    int r = 0;
    do
    {
       int a = rand(5) - 1; //uniformly at random from 0 to 4
       int b = rand(5) - 1;  //uniformly at random from 0 to 4
       r = 5*b + a;  //uniformly at random from 0 to 24
    }
    while (r >= 21); // in this event, we have to roll again
   //postcondition of loop: we have a number uniformly at random between 0 and 20

  return r % 7 + 1; 
  
  //there are 3 numbers in [0, 20] for each possible return value
  //so each has equal probability.      
}

 

确保每一步都是distribution uniformly.

rand(5) -> rand(7)

原文:http://www.cnblogs.com/leetcode/p/4008961.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!