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.
The shuffle() function randomizes the order of the elements in the array. This function assigns new keys for the elements in the array.
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)); ?>
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With