Skip to content

Instantly share code, notes, and snippets.

@nrctkno
Last active April 25, 2023 23:53
Show Gist options
  • Save nrctkno/fa52e2f3f57de9f0c1fd6ff2b3661b41 to your computer and use it in GitHub Desktop.
Save nrctkno/fa52e2f3f57de9f0c1fd6ff2b3661b41 to your computer and use it in GitHub Desktop.
Get distribution-based random element in PHP
<?php
function randomWithDistribution(array $elements) {
if(array_sum($elements) !== 100) {
throw new \Exception('randomWithDistribution: sum of probabilities must be 100');
}
$random = rand(1, 100);
$tot = 0;
foreach($elements as $id => $weight) {
$tot += $weight;
if($random <= $tot) {
return $id;
}
}
}
/**
* Test
*/
//initialize the table of results
$rounds = ['a'=>0, 'b'=>0, 'c'=>0];
//populate the results by applying the function
for($i=0; $i<10000; $i++) {
$v = randomWithDistribution(['a'=>15, 'b'=>70, 'c'=>15]);
$rounds[$v]++;
}
//render the results
echo '<pre>';
foreach($rounds as $id => $count) {
$percent = $count / 100 * count($rounds);
echo str_pad($id, 2, '000', STR_PAD_LEFT), '. ', str_repeat('-', $percent), $count, ' .. ', $percent, '%<br />';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment