1. 程式人生 > 其它 >LeetCode 470 Implement Rand10() Using Rand7()

LeetCode 470 Implement Rand10() Using Rand7()

技術標籤:LeetCode Random()LeetCodeJava

we are given the API rand7() that generates a uniform random integer in the range of [1, 7].
now we need to implement rand10() just using this API.

follow up: minimize the number of calls to rand7().

idea:
first, we need to think about how to generate rand10() from rand7()?

let us think about this: rand10() means we can uniformly choose from1 to 10.
so that means, if we have a rand11(), that would be much easier for us, because, each time we just use rand11(), and if the number we get is 11, then discard it, if not, then we can use it. and it is uniformly distributed.
so how to make rand7() become randX() which X is larger or equals to 10.

so we want randomly get from [1, 7] to [1, X] which X larger or equals to 10.

so, can we2? no, that makes [1, 7] to [2, 14]
can we do rand7 twice and get the num each time, and added it up? that the same as the last one, so it’s not gonna work.
if add didn’t work, then can we do multiple? rand7()
rand7()? that will do from [1, 49] but there are many duplicates in that, like 12 and 2

1. but we can know from this that (x,y) pair is uniformly distributed each time. so that way to transfer from cooridinate to unique numbers is: 7 * (rand7() - 1) + rand7().
that thing will project (x, y) into [1, 49], and each one of the (x, y) represents a unique number in this space.
now, since we have the rand49(), so if we want 1 to 10 uniformly, then we are gonna do rand49() % 10, so 1 will appear on 1, 11, 21, 31, 41 and 2 will appear on 2 12 22 32 42 and 9 will appear on 9, 19, 29, 39, 49…however, 0 will appear on 10, 20, 30, 40 which only fours times, so not okay, so we have to make a limit, each time, if the num>40, then we discard it.
so based on those idea, we got the following solution:

class Solution extends SolBase {
    public int rand10() {
        
        int num = Integer.MAX_VALUE;
        
        while (num > 40) {
            num = 7 * (rand7() - 1) + rand7();
        }
        return num % 10;
    }
}

但是不對!為什麼呢?因為我們實際上要的是10, 不是0!而10永遠不會出現! 所以每次0出現 我們就把他替換成10
現在就可以了。

class Solution extends SolBase {
    public int rand10() {
        
        int num = Integer.MAX_VALUE;
        
        while (num > 40) {
            num = 7 * (rand7() - 1) + rand7();
        }
        return num % 10 == 0 ? 10: num % 10;
    }
}