Given a function RAND5 that generates random numbers in the range 0 to 5 write a function RAND7?
来源:互联网 发布:linux ifup eth0 编辑:程序博客网 时间:2024/06/01 07:37
第一想法是用RAND5产生7个0-5的随机数,再除以5,得到新的0-7的随机数。但仔细想想,就会发现这个方法产生的随机数不是平稳分布的。
方法二:
RAND5有六个不同的结果;两个RAND5有6*6=36个不同的组合;三个呢,6*6*6=216个不同的组合,而且这216个组合的几率是一样的。构造一个三位的六进制数,我们很容易的就可以得到均匀分布的216个数0-215。如果我们把它们均等地分成8份(216刚好可以被8整除),就得到了8个随机数0-7。
方法三:
我们需要的结果0-7刚好是8个不同的数字,3个字节的二进制数。我们可以把RAND5的结果分成均等的两组,0-2对应0,3-5对应1。呼叫RAND5三次即可产生我们需要的二进制数。
扩展:如果提供的是RAND4而不是RAND5呢,如果要构造的是RAND6呢?
方法二不再适用,因为我们无法创建一组均等分布的且刚好可以分成七份的组合。方法三的思想还是有效,稍微修改即可:RAND4的结果可以分成三组,0-1,对应0,3-4,对应1,如果是2的话,重试;如果最后得到7的话,从头开始。
- Given a function RAND5 that generates random numbers in the range 0 to 5 write a function RAND7?
- CareerCup Write a function that given a position returns the digit in that 0123456789101112131415..
- Given an array nums, write a function to move all 0's to the end of it while maintaining the relativ
- Write a method that counts the number of occurrences of a given character in a string
- Given an integer, write a function to determine if it is a power of two.
- Given an integer, write a function to determine if it is a power of two
- Write a function that takes a string as input and returns the string reversed.
- Given two binary trees, write a function to check if they are equal or not.
- Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthe
- leetCode Given an integer (signed 32 bits), write a function to check whether it is a power of 4
- How do you design a rand7 function
- How to use the pointer of function in a class?
- Write a function that computes log2() using sqrt()
- The "data" option should be a function that returns a per-instance value in component definitions.
- Write a function to find the depth of a binary tree
- Write a function to find the depth of a binary tree
- random numbers (Expand a random range from 1–5 to 1–7)
- Given two strings s and t, write a function to determine if t is an anagram of s.
- fedora root账户不能使用gedit的解决方法
- 如何修改设备驱动的加载顺序
- Snappy主包含文件 [snappy/snappy.h]
- 图片滚动栏(JS)
- Struts2_1400_DefaultAction 关于Default Action
- Given a function RAND5 that generates random numbers in the range 0 to 5 write a function RAND7?
- Linux关于总线、设备、驱动的注册顺序
- 算法题30 颠倒栈
- 在浏览器显示时钟
- 简单的新闻栏切换窗(JQuery)
- 好事还是坏事-JDK5对泛型的引入
- 网站开发人员应该知道的61件事
- 微妙
- acm,poj中不容易发现的runtime error解决方法