Skip to content

Instantly share code, notes, and snippets.

@MrMaz
Last active December 17, 2015 04:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MrMaz/5548549 to your computer and use it in GitHub Desktop.
Save MrMaz/5548549 to your computer and use it in GitHub Desktop.
Weighted random algorithm
<?php
/**
* @param array $items
* @param integer $multiplier
* @return integer
*/
function random_weighted( $items, $multiplier = 1000 )
{
$offset = 0;
$total = array_sum( $items );
$rand = rand( 0, $multiplier - 1 );
foreach( $items as $item ) {
$offset += ( $item / $total ) * $multiplier;
if ( $rand <= $offset ) {
return $item;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment