-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathProblem15.java
55 lines (44 loc) · 1.15 KB
/
Problem15.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.util.Random;
/***
* This problem was asked by Facebook.
*
* Given a stream of elements too large to store in memory, pick a random element from the stream with uniform probability.
*/
public class Problem15 {
public static void main(String[] args) {
int[] stream = {99, 50, 20, 34, 53, 234};
RandomPicker<Integer> picker = new RandomPicker<>();
// Mimicking a stream of incoming elements
picker.pick(stream[0]);
picker.pick(stream[1]);
picker.pick(stream[2]);
picker.pick(stream[3]);
picker.pick(stream[4]);
picker.pick(stream[5]);
int random = picker.get();
System.out.println(random);
}
}
class RandomPicker<T> {
private Random gen;
private int count;
private T result;
RandomPicker() {
count = 0;
gen = new Random();
}
T get() {
return result;
}
void pick(T next) {
count++;
if (count == 1) {
result = next;
} else {
int random = gen.nextInt(count);
if (random == count - 1) {
result = next;
}
}
}
}