note 111252 added to function.mt-rand
| From: | maxim at meta dot ua | Date: | Wed, 30 Jan 2013 13:10:20 +0000 |
| Subject: | note 111252 added to function.mt-rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-193446@lists.php.net to get a copy of this message | ||
Useful way to use the:
<?php
/**
* Returns a random key, the probability of which is calculated according to a weighting factor.
* weightedIndex(array(90,10)) with a probability of 90% will return 0, and a 10% return 1
* weightedIndex(array('a'=>5,'b'=>9.5,'c'=>85.5)) with a
probability of 85.5% of the returns 'c'
*
* @param array $p an array of keys and their corresponding probabilities
*
* @return mixed random array key
*/
function weightedIndex( array $p )
{
$maxWeight = array_sum( $p );
$indexes = array_keys( $p );
$rand = mt_rand() / mt_getrandmax() * $maxWeight;
$count = count( $p );
$prevp = 0;
// do not check the last item, as if previous not worked, it will return the default
for ( $i = 0; $i < $count - 1; $i++ )
{
if ( $p[$indexes[$i]] == 0 )
{
continue;
}
$p[$indexes[$i]] += $prevp;
if ( $rand <= $p[$indexes[$i]] )
{
return $indexes[$i];
}
$prevp = $p[$indexes[$i]];
}
return $indexes[$count - 1];
}
?>
----
Server IP: 69.147.83.199
Probable Submitter: 195.24.142.156
----
Manual Page -- http://php.net/manual/en/function.mt-rand.php
Edit -- https://master.php.net/note/edit/111252
Del: integrated -- https://master.php.net/note/delete/111252/integrated
Del: useless -- https://master.php.net/note/delete/111252/useless
Del: bad code -- https://master.php.net/note/delete/111252/bad+code
Del: spam -- https://master.php.net/note/delete/111252/spam
Del: non-english -- https://master.php.net/note/delete/111252/non-english
Del: in docs -- https://master.php.net/note/delete/111252/in+docs
Del: other reasons-- https://master.php.net/note/delete/111252
Reject -- https://master.php.net/note/reject/111252
Search -- https://master.php.net/manage/user-notes.php