首页 > 代码库 > rand(5) -> rand(7)
rand(5) -> rand(7)
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)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。