1

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);
Luiz Felipe
  • 31
  • 1
  • 6
  • Is there any possible way of doing it without having to read the whole array again each time i shuffle it? – Luiz Felipe Sep 02 '12 at 22:56
  • actually I wouldn't amaze that php had `shuffle_without_same_value_before` function, as it has already some strange one. But in this case - no, it doesn't. And you have to do that manually. – zerkms Sep 02 '12 at 22:58
  • Do you want an array that doesn't have any values with their old index, or an array that doesn't have any values equal to their index? – Waleed Khan Sep 02 '12 at 22:58
  • @arxanas i need an array without the same value before or after, not the key. – Luiz Felipe Sep 02 '12 at 22:59

2 Answers2

0

Even though php has really a lot of strange functions - it doesn't have any for described situation.

So you have to do that manually.

PS: also it would be a good idea to check if it's even possible to shuffle input array in an expected way so you wouldn't get into an infinite loop.

zerkms
  • 249,484
  • 69
  • 436
  • 539
0

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
Community
  • 1
  • 1
Waleed Khan
  • 11,426
  • 6
  • 39
  • 70