我怎样才能通过提供种子随机在PHP中的数组,并得到相同的顺序? [英] How can I randomize an array in PHP by providing a seed and get the same order?

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

问题描述

我试图创建一个基于固定字符串随机字符串。我想可以,如果可能的话,创建同一个随机字符串(我知道它的一个矛盾)提供我使用相同的种子。像这样:

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.

通常情况下,你不应该试图拿出自己的算法,以随机的东西,因为他们很可能有偏差。 rel=\"nofollow\">费雪耶茨算法

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

在php7字符串的功能相同。

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天全站免登陆