470. Implement Rand10() Using Rand7()

https://leetcode.com/problems/implement-rand10-using-rand7/description/

思想如图,调用两次rand7,横竖生成一个矩阵,相当于生成49个等概率的格子,然后每十个一切,前40个看成一个整体,能保证落在前40个[1, 10]都是等概率的(即相同数目个1, 2, 3, ...,10)。如果落在了后面9个格子,相当于这次作废,重头采样。这个思想叫做Rejection Sampling。

/*
 * @lc app=leetcode id=470 lang=cpp
 *
 * [470] Implement Rand10() Using Rand7()
 */
// The rand7() API is already defined for you.
// int rand7();
// @return a random integer in the range 1 to 7

class Solution {
public:
    int rand10() {
        int index = INT_MAX;
        while (index >= 40) {
            index = 7 * (rand7() - 1) + (rand7() - 1);
        }   
        return index % 10 + 1;
    }
};

Last updated