470. 用 Rand7() 实现 Rand10()

已有方法 rand7 可生成 1 到 7 范围内的均匀随机整数,试写一个方法 rand10 生成 1 到 10 范围内的均匀随机整数。
不要使用系统的 Math.random() 方法。
答案:

  1. /**
  2. * The rand7() API is already defined in the parent class SolBase.
  3. * public int rand7();
  4. * @return a random integer in the range 1 to 7
  5. */
  6. class Solution extends SolBase {
  7. public int rand10() {
  8. int res=0;
  9. while(true){
  10. res=(rand7()-1)*7+rand7(); //取得1-49的随机数
  11. if(res<=40){ //剔除大于40的随机数字
  12. break;
  13. }
  14. }
  15. return (res%10)+1; //获得1-10的随机数字
  16. }
  17. }

思路要点:
1、res=(rand7()-1)*7+rand7(); 获取1-49随机数
rand7()-1获得0-6的随机数,(rand7()-1)*7获取的是0、7、14、21、28、35、42均匀分布的随机数,在此基础上加上随机的1-7,就得到均匀分布的1-49的随机数
注意:不能说rand7()+rand7()这种就是2-14了,不是均匀分布的,比如得到2或14的概率最小
2、if(res<=40){break;} 剔除大于40的随机数字,再使用取余的方法 (res%10)+1; 获得1-10的随机数字
也可以直接if(res<=10){break;} 来获得1-10的随机数字,但是这样会while循环很久,效率会降低。

https://www.nowcoder.com/discuss/687400?type=post&order=time&pos=&page=1&ncTraceId=&channel=-1&source_id=search_post_nctrack&subType=2
这个面经里还提到了rand5()到rand7(),应该是同理的

  1. class Solution extends SolBase {
  2. public int rand7() {
  3. int res=0;
  4. while(true){
  5. res=(rand5()-1)*5+rand5(); //取得1-25的随机数
  6. if(res<=21){ //剔除大于21的随机数字
  7. break;
  8. }
  9. }
  10. return (res%7)+1; //获得1-7的随机数字
  11. }
  12. }