Skip to content

Instantly share code, notes, and snippets.

@Miesvanderlippe
Created February 20, 2015 08:28
Show Gist options
  • Save Miesvanderlippe/e57119a151bd26e6d250 to your computer and use it in GitHub Desktop.
Save Miesvanderlippe/e57119a151bd26e6d250 to your computer and use it in GitHub Desktop.
Draw a prize with predifined chances.
$aChances = [
0 => [
'perc' => 25,
'chance' => 650
],
1 => [
'perc' => 50,
'chance' => 220
],
2 => [
'perc' => 75,
'chance' => 25
],
3 => [
'perc' => 100,
'chance' => 1
]
];
function randomDiscount( $discounts)
{
$range = 0;
foreach( $discounts as $discount)
{
$range += $discount['chance'];
/* Enter the prize somewhere on the chance line */
$prizes[ $range] = $discount['perc'];
}
$win = rand( 1, $range);
foreach( $prizes as $chance => $discount)
{
if( $win <= $chance)
{
return ( $discount);
}
}
}
/* Benchmark */
$results = [
25 => 0,
50 => 0,
75 => 0,
100 => 0
];
//print( randomDiscount($aChances));
for ( $i = 1; $i < 40000; $i++)
{
$results[ randomDiscount($aChances)] += 1;
}
print('<pre>');
print_r( $results);
print('</pre>');
die();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment