【问题标题】:How to grab lottery ball naturally如何自然地抓住彩票球
【发布时间】:2016-02-15 08:28:30
【问题描述】:
<?php

class Lottery
{
    private $start;
    private $end;

    public function __construct($start = 1, $end = 49)
    {
        $this->start = $start;
        $this->end = $end;
    }

    public function balls($num = 5)
    {
        $balls = range($this->start, $this->end);
        shuffle($balls);
        $index = array_rand($balls, $num);
        $result = [];

        for ($i = 0; $i < $num; ++$i) {
            $result[] = $balls[$index[$i]];
        }

        $result = implode(', ', $result);

        return $result;
    }
}

这就是我得到我的彩票球的方式,我的朋友告诉我,随着游戏越来越多,如果你通过内置函数随机会有一些规则可循,是真的吗?以及如何预防。

更新代码

<?php

class Lottery
{
    private $start;
    private $end;
    public $tempBalls = [];

    public function __construct($start = 1, $end = 49)
    {
        $this->start = $start;
        $this->end = $end;
    }

    public function balls($num = 5)
    {
        $balls = range($this->start, $this->end);
        $results = [];

        do {
            $results[] = $this->randBall($balls);
        } while (count($results) < $num);

        $result = implode(', ', $results);
        $this->tempBalls = [];

        return $result;
    }

    private function randBall($range)
    {
        $ball = $range[mt_rand(0, count($range) - 1)];

        if (!in_array($ball, $this->tempBalls)) {
            $this->tempBalls[] = $ball;
        } else {
            return $this->randBall($range);
        }

        return $ball;
    }
}

【问题讨论】:

标签: php


【解决方案1】:

我没有使用 shuffle() 进行测试,但肯定 rand() 函数将始终返回相同的数字序列,除非您首先使用 set a seed value。检查这是否适用于 shuffle() 应该很简单。

如果您阅读文档,您会看到 rand() 返回一个 伪随机数 并包含有关不使用它进行加密的警告。如果您考虑一个更简单的情况,其中 rand 总是从集合 {0,1,2,3,4,5} 返回一个数字,然后环绕,只是从随机偏移量开始,那么很明显这会破坏加密的点,确实改变了数字的顺序初始设置并没有真正影响这么大。

但其中有多少实际上适用于彩票球?首先,没有任何加密知识的人会使用这么小的范围来生成这样一个范围内的随机数。其次,您并没有试图保护数据的机密性。

您用于选择号码的随机数不会影响结果。

您为加密选择的随机数确实会影响结果。

关于公平性可能还有其他考虑。您不会说您是作为彩票客户选择价值还是选择中奖号码。后者意味着您必须能够证明您的代码中没有内在缺陷。我说过 rand() 返回一组可预测的数字,但是在播种 requires a very large set of numbers to be known 时它的输出(在 rand() 的情况下,模式在 2^31 之后重复),或者要知道种子值以便要预测的值。

无论如何,请使用 mt_rand() 或 openssl_random_pseudo_bytes() 但它不会对您的项目产生任何功能差异。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多