码迷,mamicode.com
首页 > 其他好文 > 详细

rand(5) -> rand(7)

时间:2014-10-07 08:16:23      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   for   sp   div   

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)

标签:style   blog   color   io   os   ar   for   sp   div   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!