PHP shuffle with seed?

后端 未结 2 801
走了就别回头了
走了就别回头了 2020-12-22 09:05

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 s

相关标签:
2条回答
  • 2020-12-22 09:41

    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)
    0 讨论(0)
  • 2020-12-22 09:43

    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
    
    0 讨论(0)
提交回复
热议问题