我知道如何在PHP中生成一个随机数,但假设我想要一个介于1-10之间的随机数,但我想要更多的3,4,5,然后是8,9,10,这怎么可能?我会发布我已经尝试过的东西,但老实说,我甚至不知道从哪里开始。
发布于 2012-08-09 04:48:03
基于@Allain的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;
}
}
}
发布于 2010-05-20 03:24:10
This tutorial通过多个剪切和粘贴解决方案,用PHP语言向您介绍了整个过程。请注意,由于下面的注释,此例程对您在该页面上找到的内容进行了轻微修改。
从post中获取的函数:
/**
* weighted_random_simple()
* Pick a random item based on weights.
*
* @param array $values Array of elements to choose from
* @param array $weights An array of weights. Weight must be a positive number.
* @return mixed Selected element.
*/
function weighted_random_simple($values, $weights){
$count = count($values);
$i = 0;
$n = 0;
$num = mt_rand(1, array_sum($weights));
while($i < $count){
$n += $weights[$i];
if($n >= $num){
break;
}
$i++;
}
return $values[$i];
}
发布于 2016-06-24 15:26:11
/**
* @param array $weightedValues
* @return string
*/
function getRandomWeightedElement(array $weightedValues)
{
$array = array();
foreach ($weightedValues as $key => $weight) {
$array = array_merge(array_fill(0, $weight, $key), $array);
}
return $array[array_rand($array)];
}
getRandomWeightedElement(array('A'=>10, 'B'=>90));
这是一个非常简单的方法。如何获得随机加权元素。我填充数组变量$key。我让$key去数组$weight x,然后用array_rand去数组。并且我有随机值;)。
https://stackoverflow.com/questions/445235
复制相似问题