php percentage chance

后端 未结 4 1093
说谎
说谎 2021-01-14 21:05

This is really more a question of approach, but I\'m presenting it in php.

Suppose we had a list of four percentages that a give event will occur on iteration.

相关标签:
4条回答
  • 2021-01-14 21:13
    $arr = array('walk the dog'=>25,'read the paper'=>25,'listen to music'=>50);
    $rand = rand(1,100);
    $sum = 0;
    $action = '';
    
    foreach ($arr as $k => $v) {
        $sum .= $k;
        if ($sum <= $k)
            $action = $v;
    }
    

    Removed those with a key value of zero, and multiplied the key-value with 100 to make it more readable.

    0 讨论(0)
  • 2021-01-14 21:15

    Have you considered using the percentage values as a cumulative number?

    $array = array('walk the dog'=>.25,'read the paper'=>.25,'drink coffee'=>.0,'listen to music'=>.50);
    
    $rand = rand();
    $cur = 0;
    foreach ($key=>$val in $array) {
      $cur += $val;
      if ($rand <= $cur)
        return $key;
    }
    

    This assumes the values in the array add up to 1. Ordering doesn't matter either...

    0 讨论(0)
  • 2021-01-14 21:22

    I'd do something like:

    $arr = array (
        'walk the dog'    =>  array('min' =>  0, 'max' =>  25),
        'read the paper'  =>  array('min' => 25, 'max' =>  50),
        'drink coffee'    =>  array('min' =>  0, 'max' =>   0),
        'listen to music' =>  array('min' => 50, 'max' => 100),
    );
    
    $rnd = rand(1,100);
    foreach($arr as $k =>$v) {
        if ($rnd > $v['min'] && $rnd <= $v['max']) {
            echo $k,"\n";
        }
    }
    
    0 讨论(0)
  • 2021-01-14 21:30

    You can restructure the array in such a way that the events are stored with decreasing probability (for performance) and the value corresponding to an event is the probability of this particular event plus the value of a previous element (which means that the last element will always have the value 1.).

    Then you just iterate over the array and return the event for which its value is greater than $rand.

    0 讨论(0)
提交回复
热议问题