Skip to content

Commit 3a42294

Browse files
committed
Added rand5 problem
1 parent e46ed55 commit 3a42294

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

src/easy-two-sigma-rand5/README.md

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# Description
2+
3+
Good morning! Here's your coding interview problem for today.
4+
5+
This problem was asked by Two Sigma.
6+
7+
Using a function `rand7()` that returns an integer from `1` to `7` (inclusive) with uniform probability, implement a function `rand5()` that returns an integer from `1` to `5` (inclusive).
8+
9+
# Source
10+
11+
Received by email from the [Daily Coding Problem](https://www.dailycodingproblem.com)

src/easy-two-sigma-rand5/java/Idea.md

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Idea behind the solution
2+
3+
Similar to the fair coin problem, we just need to use the function `rand7()` until we get something between `1` and `5` since we were told in advance that `rand7()` is already supposed to be unbiased.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
4+
public class Solution {
5+
6+
static int rand7() {
7+
return (int) (Math.random() * 6d + 1d);
8+
}
9+
10+
static int rand5() {
11+
12+
int number;
13+
do {
14+
number = rand7();
15+
} while (number > 5);
16+
17+
return number;
18+
}
19+
20+
static void printKeyMap(int key, int value) {
21+
System.out.println(key + ":" + value);
22+
}
23+
24+
public static void main(String[] args) {
25+
26+
Map<Integer, Integer> count = new HashMap<>();
27+
for (int i = 0; i < 500; i++) {
28+
final int num = rand5();
29+
final int current = count.getOrDefault(num, 0);
30+
count.put(num, current + 1);
31+
}
32+
33+
count.forEach(Solution::printKeyMap); // On average each will have a count of more or less 100
34+
}
35+
36+
}

0 commit comments

Comments
 (0)