Monday 3 September 2018

PHP: Shuffle array, so no value is like the corresponding one

There is an array with names, for example:

$donalds_nephews = array('Huey', 'Dewey', 'Louie');
array
(
    [0] => Huey
    [1] => Dewey
    [2] => Louie
)

I want to shuffle this array, but ensure that no value of the original array has the same key as the shuffled one.
$donalds_nephews_shuffled = shuffle($donalds_nephews);

This could result in 6 possible permutations:
  1. Huey, Dewey, Louie
  2. Huey, Louie, Dewey
  3. Dewey, Louie, Huey
  4. Dewey, Huey, Louie
  5. Louie, Dewey, Huey
  6. Louie, Huey, Dewey
1st, 2nd, 4th and 5th must not be the result.
What's the best way to do so? It's for Secret Santa.

Shuffle the original array, then make a copy of it and shift all entries one over, then match the two back together to get your matches.

0 comments:

Post a Comment