How can I randomize an array in PHP by providing a

2019-01-23 18:35发布

问题:

I am trying to create a "random" string based on a fixed string. I'd like to be able, if at all possible, create the same random string (i know its an oxymoron) provided I use the same seed. like so:

    $base = '0123456789abcdef';
    $seed = 'qwe123';

    function get_seeded_random_string($base, $seed){
        ???
    }

The expected behavior would be that as long as I give the same $base and $seed I always get the same random string.

回答1:

Sorry, but accordingly to the documentation the shuffle function is seeded automatically.

Normally, you shouldn't try to come up with your own algorithms to randomize things since they are very likely to be biased. The Fisher-Yates algorithm is known to be both efficient and unbiased though:

function fisherYatesShuffle(&$items, $seed)
{
    @mt_srand($seed);
    $items = array_values($items);
    for ($i = count($items) - 1; $i > 0; $i--)
    {
        $j = @mt_rand(0, $i);
        $tmp = $items[$i];
        $items[$i] = $items[$j];
        $items[$j] = $tmp;
    }
}

Same function for a string in php7

function fisherYatesShuffle(string &$items, int $seed)
{
    @mt_srand($seed);
    for ($i = strlen($items) - 1; $i > 0; $i--)
    {
        $j = @mt_rand(0, $i);
        $tmp = $items[$i];
        $items[$i] = $items[$j];
        $items[$j] = $tmp;
    }
}


回答2:

Yes, with mt_srand you can specify the seed for the "better" random number generator mt_rand.