-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathRandom_Pick_with_Weight.cpp
More file actions
35 lines (33 loc) · 908 Bytes
/
Random_Pick_with_Weight.cpp
File metadata and controls
35 lines (33 loc) · 908 Bytes
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
class Solution {
public:
vector<int> pSum;
int total = 0;
mt19937 rng{random_device{}()};
uniform_int_distribution<int> uni;
Solution(vector<int> w) {
for (int weight : w) {
total += weight;
pSum.push_back(total);
}
uni = uniform_int_distribution<int>{0, total - 1};
}
int pickIndex() {
int target = uni(rng);
int low = 0, high = (int)pSum.size() - 1;
int lowerBound = high;
while (low <= high) {
int mid = low + (high - low) / 2;
if (target >= pSum[mid]) {
low = mid + 1;
} else {
lowerBound = mid;
high = mid - 1;
}
}
return lowerBound;
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(w);
* int param_1 = obj.pickIndex();
*/