Skip to content

Instantly share code, notes, and snippets.

@vertexvaar
Last active October 20, 2021 12:03
Show Gist options
  • Save vertexvaar/2fb29ea47fcae0022758076f75f1dd5e to your computer and use it in GitHub Desktop.
Save vertexvaar/2fb29ea47fcae0022758076f75f1dd5e to your computer and use it in GitHub Desktop.
Making random fair again - for sorin
<?php
$original = $elements = [
'A' => 100,
'B' => 80,
'C' => 60,
'D' => 5,
];
function chooseElementFromWeightedList(array $list)
{
$overallProbability = array_sum($list);
$point = rand(0, $overallProbability);
asort($list);
$tmp = 0;
foreach ($list as $element => $weight) {
if ($point < ($weight + $tmp)) {
return $element;
}
$tmp += $weight;
}
return $element;
}
function shouldReset(array $elements, array $stats): bool
{
foreach ($elements as $element => $score) {
if (!isset($stats[$element])) {
return false;
}
if ($stats[$element] <= $score) {
return false;
}
}
return true;
}
for ($i = 0; $i < 1000; $i++) {
$selected = chooseElementFromWeightedList($elements);
foreach ($elements as $element => &$score) {
if ($element !== $selected) {
$score++;
}
}
unset($score);
$elements[$selected] = $original[$selected];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment