Friday, 10 August 2018

Biased Random Value From Array With PHP

  1. function biasedRandom($numbers){
  2. $total = 0;
  3. foreach($numbers as $number=>$weight){
  4. $total += $weight;
  5. $distribution[$number] = $total;
  6. };
  7. $rand = mt_rand(0,$total-1);
  8. foreach($distribution as $number=>$weights){
  9. if($rand
  10.  
  11. This function is used in the following way.
  12.  
  13. //set up array
  14. $array = array('one'=>100,
  15. 'two'=>100,
  16. 'three'=>100,
  17. 'four'=>500);
  18.  
  19. // get biased random number
  20. echo biasedRandom($array);
  21.  
  22. The key that is generated the most by the function is four because it has a higher value than the rest and will therefore 'weigh' a lot more.

0 comments:

Post a Comment