X-Git-Url: https://git.cyclocoop.org/?a=blobdiff_plain;f=includes%2FArrayUtils.php;h=985271f70997ab1e58885e04e0142d194bb7dbae;hb=93cb656139efbe9325cf868dcd4132354f2db99c;hp=d1b72a02b7ace35b2f59bded05cd73948b365062;hpb=1c4587aabfc7e6d00171062214f5887f0e8d7ede;p=lhc%2Fweb%2Fwiklou.git diff --git a/includes/ArrayUtils.php b/includes/ArrayUtils.php index d1b72a02b7..985271f709 100644 --- a/includes/ArrayUtils.php +++ b/includes/ArrayUtils.php @@ -21,7 +21,7 @@ class ArrayUtils { * various consistent hash implementations that existed before this * function was introduced. */ - static function consistentHashSort( &$array, $key, $separator = "\000" ) { + public static function consistentHashSort( &$array, $key, $separator = "\000" ) { $hashes = array(); foreach ( $array as $elt ) { $hashes[$elt] = md5( $elt . $separator . $key ); @@ -30,4 +30,40 @@ class ArrayUtils { return strcmp( $hashes[$a], $hashes[$b] ); } ); } + + /** + * Given an array of non-normalised probabilities, this function will select + * an element and return the appropriate key + * + * @param $weights array + * + * @return bool|int|string + */ + public static function pickRandom( $weights ) { + if ( !is_array( $weights ) || count( $weights ) == 0 ) { + return false; + } + + $sum = array_sum( $weights ); + if ( $sum == 0 ) { + # No loads on any of them + # In previous versions, this triggered an unweighted random selection, + # but this feature has been removed as of April 2006 to allow for strict + # separation of query groups. + return false; + } + $max = mt_getrandmax(); + $rand = mt_rand( 0, $max ) / $max * $sum; + + $sum = 0; + foreach ( $weights as $i => $w ) { + $sum += $w; + # Do not return keys if they have 0 weight. + # Note that the "all 0 weight" case is handed above + if ( $w > 0 && $sum >= $rand ) { + break; + } + } + return $i; + } }