Random number generator in arbitrary probability distribution fashion | Utility function to find ceiling of r in arr [ l . . h ] ; Same as mid = ( l + h ) / 2 ; The main function that returns a random number from arr [ ] according to distribution array defined by freq [ ] . n is size of arrays . ; Create and fill prefix array ; prefix [ n - 1 ] is sum of all frequencies . Generate a random number with value from 1 to this sum ; Find index of ceiling of r in prefix array ; Driver code ; Let us generate 10 random numbers accroding to given distribution
function findCeil ( arr , r , l , h ) { let mid ; while ( l < h ) { mid = l + ( ( h - l ) >> 1 ) ; ( r > arr [ mid ] ) ? ( l = mid + 1 ) : ( h = mid ) ; } return ( arr [ l ] >= r ) ? l : - 1 ; } function myRand ( arr , freq , n ) { let prefix = [ ] ; let i ; prefix [ 0 ] = freq [ 0 ] ; for ( i = 1 ; i < n ; ++ i ) prefix [ i ] = prefix [ i - 1 ] + freq [ i ] ; let r = Math . floor ( ( Math . random ( ) * prefix [ n - 1 ] ) ) + 1 ; let indexc = findCeil ( prefix , r , 0 , n - 1 ) ; return arr [ indexc ] ; } let arr = [ 1 , 2 , 3 , 4 ] ; let freq = [ 10 , 5 , 20 , 100 ] ; let i ; let n = arr . length ; for ( i = 0 ; i < 5 ; i ++ ) document . write ( myRand ( arr , freq , n ) ) ;