[转]PHP权重算法-用于游戏根据权限来随机物品
假设有数据:
$data = array(
array(‘id’ => 1, ‘name’ => ‘张三’, ‘weight’ => 5),
array(‘id’ => 2, ‘name’ => ‘王五’, ‘weight’ => 10),
array(‘id’ => 3, ‘name’ => ‘李四’, ‘weight’ => 15),
);
array(‘id’ => 1, ‘name’ => ‘张三’, ‘weight’ => 5),
array(‘id’ => 2, ‘name’ => ‘王五’, ‘weight’ => 10),
array(‘id’ => 3, ‘name’ => ‘李四’, ‘weight’ => 15),
);
要随机取出其中一条,并且不是完全随机,而是根据其中weight的数值,按照数值越大,几率越高的规律取出。
以前写过一些权重算法,可是都不完美,要么数据量有限制,要么weight之和必须等于一个指定的数等等,都不完善。
今天突发奇想,写了一套完美的权重算法,该算法有如下优势:
1.支持无限多个数据
2.weight值之和任意
3.不存在两个weight值一样时无法平均分配的bug
算法如下:
1 $weight = 0;
2 $tempdata = array();
3 foreach ($data as $one) {
4
5 $weight += $one['weight'];
6
7 for ($i = 0; $i < $one['weight']; $i ++) {
8 $tempdata[] = $one;
9
10 }
11
12 }
13 $use = rand(0, $weight – 1);
14 $one = $tempdata[$use];
15
2 $tempdata = array();
3 foreach ($data as $one) {
4
5 $weight += $one['weight'];
6
7 for ($i = 0; $i < $one['weight']; $i ++) {
8 $tempdata[] = $one;
9
10 }
11
12 }
13 $use = rand(0, $weight – 1);
14 $one = $tempdata[$use];
15
最终得到的$one,就是源数据数组中按照权重分配,随机得到的数据。