【发布时间】: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;
}
}
【问题讨论】:
-
is that true?是的,计算机中不存在真正的随机性。how to prevent that你不能,你只能希望你的RNG没有缺陷 -
这可能有助于让它更“随机”:stackoverflow.com/questions/25799466/…
-
如果你使用/切换到 php 7,你可以改进它:php.net/manual/en/function.random-int.php
-
我重写了代码,请帮我看看行不行
标签: php