Skip to content

Instantly share code, notes, and snippets.

@YavorK
Last active November 25, 2018 08:45
Show Gist options
  • Save YavorK/c5e5514c9c802efeab40d2d8e3088290 to your computer and use it in GitHub Desktop.
Save YavorK/c5e5514c9c802efeab40d2d8e3088290 to your computer and use it in GitHub Desktop.
<?php
$percentages = [
'Milk' => 50,
'Coffee' => 30,
'Water' => 20,
];
$percentSum = 0;
foreach ($percentages as $valuePercent) {
$percentSum = $percentSum + $valuePercent;
}
if ($percentSum > 100) {
echo 'The sum of the percentages cannot be more than 100. Current sum is ' . $percentSum;
exit;
}
$boundaries = [];
$last = null;
foreach ($percentages as $name => $chance) {
//if there was no last boundary added
if($last === null){
$boundaries[$name . '_down'] = 1;
} else {
$boundaries[$name . '_down'] = $last + 1;
}
$boundaries[$name . '_up'] = $last + $chance;
//update last reached number
$last = $boundaries[$name . '_up'];
}
echo 'Boundaries:<br>';
foreach ($boundaries as $boundaryKey => $boundaryValue) {
echo $boundaryKey . ' boundary is ' . $boundaryValue . "<br>";
}
$randomNumber = rand(1, 100);
echo '<br>';
foreach ($percentages as $name => $key) {
if ($boundaries[$name . '_down'] <= $randomNumber && $randomNumber <= $boundaries[$name . '_up']) {
echo "You got: " . $name . '<br>';
echo 'Lower boundary is: ' . $boundaries[$name . '_down'] . '<br>';
echo 'Your number was: ' . $randomNumber . '<br>';
echo 'Upper boundary is: ' . $boundaries[$name . '_up'] . '<br>';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment