1

I've been searching for this for a while but none of the solutions I've found match what I'm looking for.

Say I have an array of names:

$names = array('zack', 'tom', 'brad', 'tim');

I'd like to randomise those names but none can end up in the same position as it started in.

the shuffle() function doesn't seem do this.

I have tried the following which is probably not the best way to do it but for some reason this didn't work?:

$names = array('zack', 'tom', 'brad', 'tim');
$names2 = array('zack', 'tom', 'brad', 'tim');

do {
  shuffle($names2);
} while($names === $names2);

I also need to keep the original array in the original order so shuffling the array and then shifting by one isn't an option.

How do i achieve a shuffle with no value remaining in it's original position?

AdamJB
  • 432
  • 7
  • 10
  • 1
    "I'd like to randomise those names but none can end up in the same position as it started in." -> In this case the result is not random, it's restricted by one rule. – Reeno Nov 02 '13 at 21:39

1 Answers1

2

This is a brute force method I came up with..

It runs shuffle until the two arrays are different.
Note that this is not ideal and can take a long time for bigger arrays:)

http://codepad.viper-7.com/c8EFOc

$names = array('zack', 'tom', 'brad', 'tim');
$names2 = $names;

while(count(array_intersect_assoc($names, $names2))) {
    shuffle($names2);
    var_dump('Array1:', $names);
    echo '<br/>';
    var_dump('Array2:', $names2);
    echo '<br/>';
}

echo 'Done!';

Edit: Also have a look at Shuffling php array without same value before or after and Shuffle list, ensuring that no item remains in same position

Community
  • 1
  • 1
Terry Seidler
  • 2,043
  • 15
  • 28