website/content.en/ChapterFour/0400~0499/0470.Implement-Rand10-Using-Rand7.md
Given a function rand7 which generates a uniform random integer in the range 1 to 7, write a function rand10 which generates a uniform random integer in the range 1 to 10.
Do NOT use system's Math.random().
Example 1:
Input: 1
Output: [7]
Example 2:
Input: 2
Output: [8,4]
Example 3:
Input: 3
Output: [8,1,10]
Note:
rand7 is predefined.n, the number of times that rand10 is called.Follow up:
rand7() function?rand7()?There is an existing method rand7 that can generate a uniform random integer in the range 1 to 7. Try to write a method rand10 to generate a uniform random integer in the range 1 to 10. Do not use the system's Math.random() method.
Notes:
Follow-up:
rand7(), implement rand10().rand7() generates 1, 2, 3, 4, 5, 6, 7 with equal probability. To obtain rand10(), i.e., generate 1-10 with equal probability. The idea is to first construct a randN(), where N must be an integer multiple of 10, and then randN % 10 can give rand10(). So we can first construct rand49() from rand7(), then filter out all values in rand49() that are greater than or equal to 40, thereby obtaining rand40(), and then take modulo 10.rand7() --> rand49() --> rand40() --> rand10():
rand7() generates 1,2,3,4,5,6,7 with equal probability.rand7() - 1 generates [0,6] with equal probability.(rand7() - 1) *7 generates 0, 7, 14, 21, 28, 35, 42 with equal probability(rand7() - 1) * 7 + (rand7() - 1) generates these 49 numbers [0, 48] with equal probabilityrandN() to implement randM(), where M>N. The steps are as follows:
randN() to implement randX(), where X ≥ M, and X is an integer multiple of M. For example, 49 > 10 in this problem;randX() to generate randM(), as in this problem: 49 —> 40 —> 10.rand3() to generate rand11(), you can first generate rand27(), then set the threshold to 22, because 22 is a multiple of 11. The way to generate rand27() is: 3 * 3 * (rand3() - 1) + 3 * (rand3() - 1) + (rand3() - 1), and finally rand11() is generated; to use rand7() to generate rand9(), you can first generate rand49(), then set the threshold to 45, because 45 is a multiple of 9. The way to generate rand49() is: (rand7() - 1) * 7 + (rand7() - 1), and finally rand9() is generated; to use rand6() to generate rand13(), you can first generate rand36(), then set the threshold to 26, because 26 is a multiple of 13. The way to generate rand36() is: (rand6() - 1) * 6 + (rand6() - 1), and finally rand13() is generated;
package leetcode
import "math/rand"
func rand10() int {
rand10 := 10
for rand10 >= 10 {
rand10 = (rand7() - 1) + rand7()
}
return rand10%10 + 1
}
func rand7() int {
return rand.Intn(7)
}
func rand101() int {
rand40 := 40
for rand40 >= 40 {
rand40 = (rand7()-1)*7 + rand7() - 1
}
return rand40%10 + 1
}