gpt4 book ai didi

php - 在 PHP 中按权重生成随机结果?

转载 作者:IT老高 更新时间:2023-10-28 12:09:49 28 4
gpt4 key购买 nike

我知道如何在 PHP 中生成随机数,但可以说我想要一个介于 1-10 之间的随机数,但我想要更多的 3、4、5 和 8、9、10。这怎么可能?我会发布我尝试过的内容,但老实说,我什至不知道从哪里开始。

最佳答案

基于@Alllain 的answer/link ,我在 PHP 中编写了这个快速函数。如果要使用非整数加权,则必须对其进行修改。

  /**
* 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 中按权重生成随机结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/445235/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com