php percentage chance

后端 未结 4 1094
说谎
说谎 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: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";
        }
    }
    

提交回复
热议问题