Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit 4a98f0d

Browse files
aQuaaQua
aQua
authored and
aQua
committed
470 finish
1 parent 39c6a29 commit 4a98f0d

File tree

4 files changed

+128
-44
lines changed

4 files changed

+128
-44
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# [470. Implement Rand10() Using Rand7()](https://leetcode.com/problems/implement-rand10-using-rand7/)
2+
3+
## 题目
4+
5+
Given a function rand7 which generates a uniform random integer in the range 1 to 7, write a function rand10which generates a uniform random integer in the range 1 to 10.
6+
7+
Do NOT use system's Math.random().
8+
9+
Example 1:
10+
11+
```text
12+
Input: 1
13+
Output: [7]
14+
```
15+
16+
Example 2:
17+
18+
```text
19+
Input: 2
20+
Output: [8,4]
21+
```
22+
23+
Example 3:
24+
25+
```text
26+
Input: 3
27+
Output: [8,1,10]
28+
```
29+
30+
Note:
31+
32+
1. rand7 is predefined.
33+
1. Each testcase has one argument:n, the number of times that rand10 is called.
34+
35+
Follow up:
36+
37+
1. What is the expected valuefor the number of calls torand7()function?
38+
1. Could you minimize the number of calls to rand7()?
39+
40+
## 解题思路
41+
42+
见程序注释
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package problem0470
2+
3+
import "math/rand"
4+
5+
func rand10() int {
6+
t := 50
7+
for t > 39 {
8+
t = 7*(rand7()-1) + (rand7() - 1)
9+
// t 的取值范围为 [0,48],每个数字出现的概率都是为 1/49
10+
}
11+
// t 的范围是 [0,39],t 出现在这个范围内的概率是 40/49
12+
// 当 t 为 3, 13, 23 或 33 的时候, t%10+1 == 4
13+
// 返回 4 的概率 = (4 * 1/49) / (40/49) == 1/10
14+
// 同理可知,返回 [1,10] 中每个数字的概率都是 1/10
15+
// 符合题意
16+
return t%10 + 1
17+
}
18+
19+
func rand7() int {
20+
return rand.Intn(7) + 1
21+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package problem0470
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
func Test_rand10(t *testing.T) {
10+
ast := assert.New(t)
11+
for i := 0; i < 100; i++ {
12+
r := rand10()
13+
ast.True(1 <= r && r <= 10)
14+
}
15+
}
16+
17+
func Benchmark_rand10(b *testing.B) {
18+
for i := 0; i < b.N; i++ {
19+
rand10()
20+
}
21+
}

0 commit comments

Comments
 (0)