Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 307
Angel S. Moreno Avatar asked Jul 03 '10 00:07

Angel S. Moreno


People also ask

How do I randomize an array order in PHP?

The shuffle() function randomizes the order of the elements in the array. This function assigns new keys for the elements in the array.

How do you shuffle an associative array in PHP?

php function shuffle_assoc($my_array) { $keys = array_keys($my_array); shuffle($keys); foreach($keys as $key) { $new[$key] = $my_array[$key]; } $my_array = $new; return $my_array; } $colors = array("color1"=>"Red", "color2"=>"Green", "color3"=>"Yellow"); print_r(shuffle_assoc($colors)); ?>

How do you shuffle an object in PHP?

Answer: Use the PHP shuffle() function You can use the PHP shuffle() function to randomly shuffle the order of the elements or values in an array. The shuffle() function returns FALSE on failure.

How do you randomize an array in Python?

Using shuffle() method from Random library to shuffle the given array. Here we are using shuffle method from the built-in random module to shuffle the entire array at once.


2 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;
    }
}
like image 188
André Laszlo Avatar answered Oct 01 '22 11:10

André Laszlo


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

like image 23
Artefacto Avatar answered Oct 01 '22 09:10

Artefacto