Skip to content

Commit a2c8bb1

Browse files
committed
feat: Solution for August Challeng 28 - Implement Rand10() Using Rand7()
1 parent dafd443 commit a2c8bb1

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*:
2+
# Implement Rand10() Using Rand7()
3+
https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/552/week-4-august-22nd-august-28th/3439/
4+
5+
---
6+
7+
### Problem Statement:
8+
9+
Given the API `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. You can only call the API `rand7` and you shouldn't call any other API. Please don't use the system's `Math.random()`.
10+
11+
Notice that Each test case has one argument `n`, the number of times that your implemented function `rand10` will be called while testing.
12+
13+
14+
15+
### Example:
16+
17+
```
18+
Input: n = 1
19+
Output: [2]
20+
21+
Input: n = 2
22+
Output: [2,8]
23+
24+
Input: n = 3
25+
Output: [3,8,10]
26+
27+
```
28+
29+
### Constraints:
30+
+ 1 <= n <= 10^5
31+
32+
### Follow up:
33+
+ What is the [expected](https://en.wikipedia.org/wiki/Expected_value) value for the number of calls to `rand7()` function?
34+
+ Could you minimize the number of calls to `rand7()`?
35+
36+
*/
37+
38+
39+
import UIKit
40+
41+
/**
42+
* The rand7() API is already defined in the parent class SolBase.
43+
* func rand7() -> Int = {}
44+
* @return a random integer in the range 1 to 7
45+
*/
46+
47+
class Solution: SolBase {
48+
func rand10() -> Int {
49+
let result = (rand7() - 1) * 7 + rand7()
50+
51+
if result <= 40 {
52+
return result % 10 + 1
53+
}
54+
55+
return rand10()
56+
}
57+
}
58+
59+
let sol = Solution()
60+
sol.rand10()
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios' display-mode='raw'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

0 commit comments

Comments
 (0)