php - Randomize weighted array with weights lower than 1 and decimals -
i have array weights on each value used retrieve random value based on weights. have used in past:
$items = array( "value1" => 30, "value2" => 70 ); $weighted = array(); foreach( $items $value => $weight ) { $weighted = array_merge($weighted, array_fill(0, $weight, $value)); } echo $result = $weighted[array_rand($weighted)];
but if need use decimals on weights? (the weights use sum 100 btw)
for example:
$items = array( "value1" => 0.5, "value2" => 99.5 );
so value1 shown 0.5% of times.
you go that: first, create decimal random number within desired precision. example, create random integer number between 0 , 10.000 , divide 100 (in case, it's precision 2 digits after comma). let's name random_value.
then (in pseudo code):
given: random_value, decimal in [0,100] sum = 0 each item in items sum += weight(item) if(sum >= random_value) return item (and break for-loop)
so if got weights (0.5, 45.5, 50) , random_value 46, add 0.5 sum, 0.5, thats not >= 46 -> go on add 45.5 sum, 50, >= 46 -> second item is
Comments
Post a Comment