如何通过提供种子并获得相同的顺序来随机化 PHP 中的数组? [英] How can I randomize an array in PHP by providing a seed and get the same order?

查看:25
本文介绍了如何通过提供种子并获得相同的顺序来随机化 PHP 中的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试基于固定字符串创建一个随机"字符串.如果可能的话,我希望能够创建相同的随机字符串(我知道它是矛盾的),前提是我使用相同的种子.像这样:

<前>$base = '0123456789abcdef';$seed = 'qwe123';函数 get_seed_random_string($base, $seed){???}

预期的行为是,只要我给出相同的 $base$seed,我总是得到相同的随机字符串.

解决方案

抱歉,但相应地 文档 随机播放功能是自动播种的.

通常情况下,您不应该尝试提出自己的算法来随机化事物,因为它们很可能存在偏见.众所周知,Fisher-Yates 算法既高效又无偏见:

function fisherYatesShuffle(&$ite​​ms, $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;}}

php7 中字符串的相同功能

function fisherYatesShuffle(string &$ite​​ms, 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;}}

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.

解决方案

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

这篇关于如何通过提供种子并获得相同的顺序来随机化 PHP 中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆