How can I randomize an array in PHP by providing a seed and get the same order?

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.

Answers


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;
    }
}

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


Need Your Help

How do you create a control during runtime on iOS

controls ios4

Is there a way to create a control during runtime? I tried something like

How to Make Sure a Space that is filled is not taken up again in a 2D array?

java arrays 2d

This is my first time on this website. I am VERY new to java and coding in general so I will most likely need in depth explanations. I am writing a program that takes 12 students and places them in...