0

How can I make the php shuffle function use a seed, so that when I use the same seed, the shuffle function will output the same array. I read that shuffle is automatically seeded. Is there a way to get the seed of that shuffle used, or how can I create/mimic shuffle with a custom seed?

Sumurai8
  • 20,333
  • 11
  • 66
  • 100
foss coffee
  • 159
  • 1
  • 4

2 Answers2

5

You can't retrieve the seed used by shuffle, but you can simulate shuffle and fix your own seed:

$array = range(1, 10);

function seededShuffle(array &$array, $seed) {
    mt_srand($seed);
    $size = count($array);
    for ($i = 0; $i < $size; ++$i) {
        list($chunk) = array_splice($array, mt_rand(0, $size-1), 1);
        array_push($array, $chunk);
    }
}

$seed = date('Ymd');
seededShuffle($array, $seed);
var_dump($array);

This will set a different seed each day, but throughout the day it will use the same seed and shuffle the array in the same order; tomorrow will be a different random shuffle to today

For today (6th June 2015), the sequence should be

3, 6, 9, 2, 7, 1, 8, 5, 10, 4
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • 1
    i would recommend to use the [fisher-yates-knuth shuffling](http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) to generate the shuffling with given seed, as it is `O(n)` , **unbiased** and does **not need** `array_splice`s which can be expensive (operates in-place) – Nikos M. Jun 06 '15 at 14:24
-1

PHP does not have shuffling with seeding, but you can do this instead:

$an_array = array('a','b','c','d');
$indices = array(0,1,2,3);

// shuffle the indices and use them as shuffling seed
shuffle($indices);

// then whenever you want to produce exactly same shuffle use the pre-computed shuffled indices
function shuffle_precomputed($a, $shuffled_indices)
{
     $b = $a; // copy array
     foreach ($shuffled_indices as $i1=>$i2) $a[$i2] = $b[$i1];
     return $a;
}

use like this:

$shuffled_array = shuffle_precomputed($an_array, $indices);

You can even use the factoradic number system to transform the $shuffled_indices array to/from a unique integer number that can be used as a unique seed, then simply compute the shuffle from the factoradic number to be used in shuffle_precomputed function.

For additional shuffle variations for PHP you may want to see:

  1. PHP - shuffle only part of an array
  2. Efficiently pick n random elements from PHP array (without shuffle)
Community
  • 1
  • 1
Nikos M.
  • 8,033
  • 4
  • 36
  • 43
  • 1
    This does not solve the problem as as the 'indices' are not a seed, as requested by the OP. – Deckard Jul 19 '16 at 12:20
  • In your solution the actual shuffling is happening at `shuffle($indices)` - wihtout a given seed. Saving the solution doesn't solve the problem either. Your solution doesn't solve the problem. – Florian Metzger-Noel Apr 19 '22 at 10:41