PHP 中的加權隨機數產生
問題:
問題:
答案:
要實現這種加權隨機性,您可以利用關聯數組將每個所需結果映射到其權重。在這種情況下,您可以建立一個數組,其中3、4 和5 的權重(例如,3 - 50%、4 - 30%、5 - 20%)高於8、9 和10(例如,8 - 10) %, 9 - 5%, 10 - 5%)。 根據分配的權重,您可以產生使用 mt_rand 在權重總和範圍內的隨機數。然後,循環遍歷數組並從隨機數中減去每個權重值,直到其變為負數。使隨機數為負數的權重對應的數組鍵就是期望的結果。/** * 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; } } }這是一個實現這種加權隨機性的 PHP 函數:
以上是如何在 PHP 中產生加權隨機數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!