Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating random results by weight in PHP?

Tags:

php

random

I know how to generate a random number in PHP but lets say I want a random number between 1-10 but I want more 3,4,5's then 8,9,10's. How is this possible? I would post what I have tried but honestly, I don't even know where to start.

like image 399
kyct Avatar asked Jan 15 '09 00:01

kyct


People also ask

How do I generate a random number in PHP?

The rand() function generates a random integer. Example tip: If you want a random integer between 10 and 100 (inclusive), use rand (10,100). Tip: As of PHP 7.1, the rand() function has been an alias of the mt_rand() function.

What is weighted random selection?

Weighted random choices mean selecting random elements from a list or an array by the probability of that element. We can assign a probability to each element and according to that element(s) will be selected. By this, we can select one or more than one element from the list, And it can be achieved in two ways.


1 Answers

Based on @Allain's answer/link, I worked up this quick function in PHP. You will have to modify it if you want to use non-integer weighting.

  /**    * getRandomWeightedElement()    * Utility function for getting random values with weighting.    * Pass in an associative array, such as array('A'=>5, 'B'=>45, 'C'=>50)    * An array like this means that "A" has a 5% chance of being selected, "B" 45%, and "C" 50%.    * The return value is the array key, A, B, or C in this case.  Note that the values assigned    * do not have to be percentages.  The values are simply relative to each other.  If one value    * weight was 2, and the other weight of 1, the value with the weight of 2 has about a 66%    * chance of being selected.  Also note that weights should be integers.    *     * @param array $weightedValues    */   function getRandomWeightedElement(array $weightedValues) {     $rand = mt_rand(1, (int) array_sum($weightedValues));      foreach ($weightedValues as $key => $value) {       $rand -= $value;       if ($rand <= 0) {         return $key;       }     }   } 
like image 68
Brad Avatar answered Sep 30 '22 23:09

Brad