How to implement Rand10 with Rand7
This article focuses on "how to use Rand7 to achieve Rand10", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "how to use Rand7 to achieve Rand10"!
The first thing to note is that the numbers 1-10 should have the same probability of generation. Since we can only use the rand7 function, the idea must be to combine the rand7 function.
If you assume:
A = rand7 () b = rand7 ()
Then the numbers 1 to 49 can be obtained by x = a + (b-1) * 7:
[[1. 8. 15. 22. twenty-nine。 thirty-six。 43.] [2. 9. 16. 23. thirty。 thirty-seven。 44.] [3. 10. 17. 24. thirty-one。 thirty-eight。 45.] [4. 11. 18. 25. thirty-two。 thirty-nine。 46.] [5. 12. 19. 26. thirty-three。 forty。 47.] [6. 13. 20. 27. thirty-four。 forty-one。 48.] [7. 14. 21. twenty-eight。 thirty-five。 forty-two。 49.]]
For the number x: 1, we can equally generate integers from 1 to 10 by (x-1)% 10 + 1:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10,1, 2, 3, 4, 5, 6, 7, 8, 9, 10,1, 2, 3, 4, 5, 6, 7, 8, 9, 10,1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
As you can see, each number appears four times. For 41-49, the simpler way to deal with it is to abandon it directly. Until the number obtained is 1 to 40. The probability p of generating 1 to 40 for each run of the program is: 40 Ex 49. According to the expectation formula of independent event Ex = np, the expected number of runs of the program is 1.225, and the rand7 function is called twice per run, so the number of calls to the rand7 function is expected to be 2.45.
The reference code is as follows:
# Created by Jedi.L# The rand7 () API is already defined for you.# def rand7 (): # @ return a random integer in the range 1 to 7class Solution: def rand10 (self): ": rtype: int"idx = 49 while idx > 40: row = rand7 () col = rand7 () idx + (col-1) * 7 if idx