php percentage chance

后端 未结 4 1095
说谎
说谎 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: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.

提交回复
热议问题