File tree 1 file changed +31
-20
lines changed
scripts/algorithms/R/Random Pick with Weight
1 file changed +31
-20
lines changed Original file line number Diff line number Diff line change 1
- var Solution = function ( w ) {
2
- this . w = [ ] ;
3
- this . total = w . reduce ( ( collector , el ) => collector + el , 0 )
4
- let start = 0
5
- for ( const el of w ) {
6
- this . w . push ( [ start , start + el ] )
7
- start = start + el
1
+ class Solution {
2
+ constructor ( nums ) {
3
+ this . map = new Map ( ) ;
4
+ this . sum = 0 ;
5
+
6
+ nums . forEach ( ( num , i ) => {
7
+ this . sum += num ;
8
+ this . map . set ( this . sum , i ) ;
9
+ } )
8
10
}
9
- } ;
10
-
11
- /**
12
- * @return {number }
13
- */
14
- Solution . prototype . pickIndex = function ( ) {
15
- const rand = Math . floor ( Math . random ( ) * this . total )
16
- for ( let i = 0 ; i < this . w . length ; i ++ ) {
17
- const pair = this . w [ i ] ;
18
- if ( pair [ 0 ] <= rand && rand < pair [ 1 ] ) {
19
- return i ;
11
+ pickIndex = function ( ) {
12
+ const random_sum = Math . floor ( Math . random ( ) * this . sum ) ;
13
+ return this . fetchIndexUsingBS ( random_sum ) ;
14
+ }
15
+ fetchIndexUsingBS = function ( target ) {
16
+ const sums = Array . from ( this . map . keys ( ) ) ;
17
+ let lo = 0 ,
18
+ hi = sums . length - 1 ,
19
+ mid ;
20
+
21
+ while ( lo <= hi ) {
22
+ mid = Math . floor ( ( hi - lo ) / 2 ) + lo ;
23
+ // if((mid === 0 || sums[mid - 1] < target) && sums[mid] >= target) {
24
+ // return this.map.get(sums[mid]);
25
+ // }
26
+ if ( sums [ mid ] > target ) {
27
+ hi = mid - 1 ;
28
+ } else {
29
+ lo = mid + 1 ;
30
+ }
20
31
}
32
+ return lo ;
21
33
}
22
-
23
- } ;
34
+ }
You can’t perform that action at this time.
0 commit comments