ani*_*mal 1 php arrays sorting random
我希望有人可以帮助我.我想采取一个有序的PHP数组并随机"摇晃"它有点改变顺序,但保留一些原始的整体结构.
想象一下,你有一个彩色亮片托盘组成一个房子的照片.如果你轻轻摇晃托盘,那么亮片会移动,但是,根据你摇晃它的多少,你仍然会保留一些房子的原始结构 - 它会更模糊.这就是我想用php数组做的事情.
让我举个例子.假设我有以下数组:
$Array=Array(
1=>15,
2=>14,
3=>13,
4=>12,
5=>11,
6=>10,
7=>9,
8=>8,
9=>7,
10=>6,
11=>5,
12=>4,
13=>3,
14=>2,
15=>1);
Run Code Online (Sandbox Code Playgroud)
我希望能够稍微摇晃一下,给出类似的东西:
$Array=Array(
1=>13,
2=>15,
3=>12,
4=>14,
5=>11,
6=>8,
7=>7,
8=>10,
9=>5,
10=>6,
11=>9,
12=>4,
13=>2,
14=>1,
15=>3);
Run Code Online (Sandbox Code Playgroud)
该订单已部分随机化,但总体下降趋势从15比1仍然存在.我希望这是有道理的.
除非我弄错了,否则我认为php中的本机函数不会这样做.但有谁知道如何实现这一目标?
您应该编写自己的算法,而不是使用类似shuffle()或array_shuffle()优化的函数来获得尽可能多的干扰效果:
试试'冒泡'策略:
这应该比严格随机化更好地保留元素的粗略位置,因为元素在每次迭代期间只能移动一步.所以应该保留一般趋势.多少取决于您执行的迭代次数.
这是一个(非常简单的)示例实现:
#!/usr/bin/php
<?php
// the input array, just as you specified it
$input=array(
1=>15,
2=>14,
3=>13,
4=>12,
5=>11,
6=>10,
7=>9,
8=>8,
9=>7,
10=>6,
11=>5,
12=>4,
13=>3,
14=>2,
15=>1
);
// the algorithm itself, a 'bubbling' function
function array_bubble (&$collection, $limit) {
for ($i=1; $i<=$limit; $i++) {
$pos=rand(min(1,sizeof($collection)-1);
$help=$collection[$pos];
$collection[$pos] =$collection[$pos+1];
$collection[$pos+1]=$help;
}
return $collection;
} // function array_bubble
// here the algorithm is called and the result printed
// note that the '20' in there is the number of iterations. Try changing it!
print_r(array_bubble($input,20));
?>
Run Code Online (Sandbox Code Playgroud)
该脚本产生如下输出:
Array
(
[1] => 11
[2] => 15
[3] => 13
[4] => 8
[5] => 14
[6] => 12
[7] => 9
[8] => 10
[9] => 5
[10] => 6
[11] => 7
[12] => 4
[13] => 1
[14] => 3
[15] => 2
)
Run Code Online (Sandbox Code Playgroud)