function MyRand( array $arr , $number ){
$sum = 0;
# 处理数组的取值范围
foreach( $arr as $key => $value ){
$sum += $value;
$new[] = $sum;
}
$return = [];
# 循环指定次数
while( $number -- ){
$rand = mt_rand( 0 , $sum - 1 );
# 查找随机数相邻最近的key值
foreach ( $new as $key1 => $value2 ) {
if( $rand < $value2 ){
$return[] = $key1;
break;
}
}
}
return $return;
}
#关于随机权重的准确性可以多生成几组随机数、计算下出现的概率
echo '<pre/>';
$new = MyRand( [ 20 , 50 , 30] , 100000 );
//print_r( $new );
$test_result = array_count_values( $new );
print_r( $test_result );
exit;
加权随机数
最新推荐文章于 2022-11-11 10:15:13 发布