File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments