php - PHP - 在关于模式 X 的区间内生成随机数
问题描述
我正在尝试生成其模式等于X(任何实数)的随机数。作为说明的一种方式,我期望一个函数的头是rand(int min, int max, int mode)
,并且当我使用以下参数调用它时会rand(min: 1, max: 6, mode: 4)
生成以下内容:
(1,2,4,4,4,5,3) // not exact, but similar
我正在寻找一种优化的方法(尽管手动操作是最坏的情况,但我没有想法)。
我检查了mt_rand()
,rand
和其他随机生成函数,但没有找到我要找的东西。
有什么建议吗?
解决方案
<?php
function generateRandomWithMode($min,$max,$mode,$size){
if(!($mode >= $min && $mode <= $max)){
throw new Exception("Mode $mode is not between $min and $max range");
}
$half_count = intval($size / 2);
/*
set mode frequency as half of the size + any random value generated between 0 and half_count. This ensures
that the mode you provided as the function parameter always remains the mode of the set of random values.
*/
$mode_frequency = $half_count + rand(0,$half_count);
$random_values = [];
$size -= $mode_frequency;
while($mode_frequency-- > 0) $random_values[] = $mode;
while($size-- > 0) $random_values[] = rand($min,$max);
shuffle($random_values);
return $random_values;
}
print_r(generateRandomWithMode(1,100,4,10));
输出
Array
(
[0] => 4
[1] => 63
[2] => 4
[3] => 4
[4] => 24
[5] => 4
[6] => 4
[7] => 4
[8] => 12
[9] => 4
)
推荐阅读
- python - 为 debian 打包时覆盖 python 参数
- java - java新手:得到意外的输出
- c# - RestSharp C# JsonDeserializer to List 将对象属性值设为空
- javascript - 您将如何比较两个数组并在两个数组之间进行过滤?
- c# - 从抽象类字段继承的类被神秘地覆盖
- javascript - Formik 测试错误:初始化 React 时定义了“document”全局,但不再定义
- mongodb - Mongoose findOneAndUpdate:更新对象数组中的一个对象
- java - String.split() 导致创建一个空字符串,我该如何防止这种情况?
- math - 为什么这个哥德巴赫猜想程序在 Prolog 中不起作用?
- java - 使用 spotify docker 客户端时如何禁用 http.wire?