Skip to content

Commit 671d71d

Browse files
committed
add: WeightedRandomSelection
1 parent c555907 commit 671d71d

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
public class WeightedRandomSelection {
2+
int[] prefixSum;
3+
4+
public WeightedRandomSelection(int[] weights) {
5+
this.prefixSum = new int[weights.length];
6+
for (int i = 0; i < weights.length; i++) {
7+
prefixSum[i] = i == 0 ? weights[i] : prefixSum[i-1] + weights[i];
8+
}
9+
}
10+
11+
private int select() {
12+
// Pick a random target between 1 and the largest endpoint on the number
13+
// line.
14+
int target = (int)(Math.random() * prefixSum[prefixSum.length - 1]) + 1;
15+
int left = 0;
16+
int right = prefixSum.length - 1;
17+
// Perform lower-bound binary search to find which endpoint (i.e., prefix
18+
// sum value) corresponds to the target.
19+
while (left < right) {
20+
int mid = (left + right) / 2;
21+
if (prefixSum[mid] < target) {
22+
left = mid + 1;
23+
} else {
24+
right = mid;
25+
}
26+
}
27+
return left;
28+
}
29+
}

0 commit comments

Comments
 (0)