Last active
June 23, 2022 22:02
-
-
Save IronGhost63/3ece8f6ab145edd257326011bac129f4 to your computer and use it in GitHub Desktop.
Random choices with weight adjustable
This file contains 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 | |
// define options with chance weight | |
$choices = [ | |
'a' => 10.50, | |
'b' => 30, | |
'c' => 24.50, | |
'd' => 35, | |
]; | |
$total = array_sum( $choices ); // total chance | |
$percent = rand( 0, $total*100 ) / 100; // random chance with decimal point | |
$award = null; | |
$carry = 0; | |
// loop through each option | |
foreach ( $choices as $key => $value ) { | |
// calculate for floor/ceil value for current option | |
$high = $carry + $value; | |
$low = $carry; | |
// check if randomized $percent inside the threshold | |
if ( $percent > $low && $percent <= $high ) { | |
$award = $key; | |
// value inside the threshold, break loop. | |
break; | |
} | |
// value outside the threshold, save next low value and continue. | |
$carry += $value; | |
} | |
// output | |
echo "percent: {$percent}\n"; | |
echo "award: {$award}\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment