洗牌PHP数组没有之前或之后相同的值 [英] Shuffling php array without same value before or after
问题描述
要洗牌PHP中的数组是容易的,但我的问题是,当我尝试将它洗了无键后,得到同样的结果了。
例如:
阵列(0 =→1,1 =大于2,2 =→3,3 =→3)
我必须有没有3走到一起的结果。
一些阵列的例子,我想:
阵列(0 =→2,1 =→3,2 =大于1,3 =→3)
我tryed检查数组的每一个项目,如果出现这种情况,我再次洗牌它,并检查其他时间。但是,这似乎是对时间和过程既浪费
编辑:
这里是code I是:
做
{
$ not_valid = FALSE;
为($ I = 0; $ I<的sizeof($ arr_times)-1; $ I ++){
如果($ arr_times [$ i] == $ arr_times [$ I + 1])
$ not_valid = TRUE;
}
如果($ not_valid)
洗牌($ arr_times);
}而($ not_valid);
从<一个href=\"http://stackoverflow.com/questions/7279895/shuffle-list-ensuring-that-no-item-remains-in-same-position\">Shuffle列表中,确保没有项目保持在相同的位置
&LT; PHP
$富=阵列(
0,
1,
2,
3,
4,
);为($ i = 0,$ C = sizeof的($ foo的); $ I&LT; $ C - 1; $ I ++){
$ new_i =兰特($ I + 1,$ C - 1);
列表($ foo的[$ i],$ foo的[$ new_i)=阵列($ foo的[$ new_i],$ foo的[$ i]);
}var_export($ foo的); //紊乱
To shuffle an array in php is easy but my problem is when i try to shuffle it without getting the same result before of after that key.
Example:
Array ( 0 => 1, 1 => 2, 2 => 3, 3 => 3 )
I must have a result without 3 coming together.
Example of some array i want:
Array ( 0 => 2, 1 => 3, 2 => 1, 3 => 3 )
I've tryed to check each item of the array, if that happens i shuffle it again, and check another time. But that seems to be waste both on time and process.
EDIT: Here is the code i use:
do
{
$not_valid=false;
for($i=0;$i<sizeof($arr_times)-1;$i++){
if($arr_times[$i]==$arr_times[$i+1])
$not_valid=true;
}
if($not_valid)
shuffle($arr_times);
}while ($not_valid);
From Shuffle list, ensuring that no item remains in same position
<?php
$foo = array(
0,
1,
2,
3,
4,
);
for ($i = 0, $c = sizeof($foo); $i < $c - 1; $i++) {
$new_i = rand($i + 1, $c - 1);
list($foo[$i], $foo[$new_i]) = array($foo[$new_i], $foo[$i]);
}
var_export($foo); // Derangement
这篇关于洗牌PHP数组没有之前或之后相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!