Last active
April 25, 2023 23:53
-
-
Save nrctkno/fa52e2f3f57de9f0c1fd6ff2b3661b41 to your computer and use it in GitHub Desktop.
Get distribution-based random element in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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