Array或阵列加权洗牌? [英] Weighted Shuffle of an Array or Arrays?
本文介绍了Array或阵列加权洗牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是好的算法,洗牌数组或使用权重从嵌套数组的数组?
What is a good algorithm that shuffles an array or arrays using weights from the nested arrays?
例如:
$array = array(
array("name"=>"John", "rank"=>3),
array("name"=>"Bob", "rank"=>1),
array("name"=>"Todd", "rank"=>8),
array("name"=>"Todd", "rank"=>14),
array("name"=>"Todd", "rank"=>4)
);
我要的阵列随机洗牌,但我想在等级
值是一个权重。因此那些具有低数秩是更可能是在列表的顶部。
I want the array randomly shuffled but I want the rank
value to be a weight. So those with a low number rank are more likely to be at the top of the list.
我已经尝试了一些事情,比如通过数组迭代,拉出使用选择阵列 mt_rand(mt_rand(0,$值),$值)
,但我不认为我是在正确的轨道上......
I've experimented with a few things, like iterating through the array and pulling out arrays chosen using mt_rand(mt_rand(0,$value),$value)
but I don't think I'm on the right track...
推荐答案
我能解决这个问题,像这样:
I was able to solve this problem like so:
function compare($a, $b)
{
$share_of_a = $a['rank'];
$share_of_b = $b['rank'];
return mt_rand(0, ($share_of_a+$share_of_b)) > $share_of_a ? 1 : -1;
}
usort($array, "compare"); // Sort the array using the above compare function when comparing
$array = array_reverse($array);
这篇关于Array或阵列加权洗牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文