核心原理:把每个概率项抽象成数学中的一个线段,N个线段的总长度就是总权重值,然后代码随机生成一个数,判断落在哪个线段的范围内,判断过程就是依次遍历N个线段,把随机出的线段长度逐步折减,减到0或负的,说明最终落在该段内。
该算法优势:空间复杂度接近0
<?php
function rolling(): array {
$conf = [
['id'=> 1,'weight'=>80],
['id'=> 2,'weight'=>10],
['id'=> 3,'weight'=>7],
['id'=> 4,'weight'=>2],
['id'=> 5,'weight'=>1]
];
$total = 0;
foreach($conf as $item) {
$total += $item['weight'];
}
$random = mt_rand(1, $total);
foreach($conf as $item) {
$random -=$item['weight'];
if(random <=0) {
return $item;
}
}
}
$randomItem = rolling();
//...