leetcode:Implement Rand10() Using Rand7()

Implement Rand10() Using Rand7()
题目:给定一个产生1-7的随机数的方法Rand7(),写出一个产生1-10的随机数的方法
分析:第一种想法是我们将两次随机结果相加扩大范围,然后选择10个某些等概率的组合映射到1-10输出问题是如果只选择单个组合,比如x = rand7()-1,y=rand7(),当且仅当x=0,y=1时输出1。这样只有 10 1 / 7 1 / 7 10*(1/7)*(1/7) 能够产生有用的输出。
参考答案:
r e s = 7 ( r a n d 7 ( ) 1 ) + r a n d 7 ( ) 1 res = 7*(rand7()-1)+rand7()-1 保证res<40时输出(保证10的倍数的范围即可)
返回:res%10+1;

证明:答案的思路是利用随机数生成任意数字的7进制的展开,只要从生成的数字范围里找出10的倍数的连续数字,再对10取余数+1即可。当然也可以使用 7 2 ( r a n d 7 ( ) 1 ) + 7 ( r a n d 7 ( ) 1 ) + r a n d 7 ( ) 1 7^2(rand7()-1)+7*(rand7()-1)+rand7()-1 等来生成更大范围的数字来达到目的。

public int rand10() {
        int base = 40 ;
        while(base>=40){
            base = 7*(rand7()-1)+rand7()-1;           
        }
        return base%10+1;
    }

猜你喜欢

转载自blog.csdn.net/weixin_32931837/article/details/88135061