【问题标题】:if multiple random numbers are all equal return true如果多个随机数都相等,则返回 true
【发布时间】:2013-09-12 14:54:10
【问题描述】:

我正在研究一些随机生成器,这有点像掷骰子,如果所有骰子返回的数字与你赢得游戏的数字相同,或者你再试一次。

为了获得六个骰子,我使用了 mt_rand 函数并分别为每个骰子,所以我有这个:

$first = mt_rand(1,6);
$second = mt_rand(1,6);
$third = mt_rand(1,6);
$fourth = mt_rand(1,6);
$fifth = mt_rand(1,6);
$sixth = mt_rand(1,6);

但我不知道如何返回多个随机生成数字的 if 操作数。

如果我会使用 2 个骰子,我会使用

if ( $first === $second ) 

如果第一个和第二个骰子都返回数字 2,则返回 true

但是,如果我想在所有 6 个骰子都返回数字 2 时回显 true,我该如何使用它?

编辑: 数字 2 只是一个例子,如果我只需要数字 2 我知道如何使用数组和变量来做到这一点,但重点是我只需要匹配所有数字,从 1 到 6 的哪个数字并不重要。第一个答案确实有效,但让我们看看是否可以使用数组。

【问题讨论】:

  • $first === $second && $second === $third && $third === $fourth ...
  • 学习使用数组会让这更容易,然后你可以使用像array_count_values()这样的函数

标签: php random operand


【解决方案1】:

使用数组让您的生活更轻松(例如,$dices 索引从 0 到 5)

只需将它放在一个循环中并在每次迭代时检查。如果一个骰子不是 2,$allDicesSameNumber 将是错误的。

$number = mt_rand(1, 6);
$allDicesSameNumber = true;
for ($i = 1; $i < 6 /* dices */; $i++) {
    $dices[$i] = mt_rand(1, 6);

    if ($dices[$i] !== $number)
        $allDicesSameNumber = false;
}

【讨论】:

  • 但是当它被锁定到数字 2 时,我需要匹配所有 6 个具有相同数字的骰子,无论哪个都无所谓。
  • 抱歉愚蠢,但这会降低获胜的机会吗,就像我现在掷 7 个骰子一样,首先我们在 $number 中生成 1 个随机数,而不是我们需要将它与其他 6 个随机生成的数字匹配?
  • @AleksandarĐorđević 不,你只需掷 6 个骰子。因为我将 $i 更改为从 1 开始而不是 0。看the diff
【解决方案2】:
$diceCount = 6;
$diceArray = array();
for($i=1; $i<=$diceCount; $i++) {
    $diceArray[] = mt_rand(1,6);
}
if (count(array_count_values($diceArray) == 1) {
    echo 'All the dice have the same number';
}

【讨论】:

  • 我得到一个错误 Allowed memory size of 134217728 bytes in line where $diceArray[] = mt_rand(1,6);
  • mea culpa.... 将 for($i=1; $i=$diceCount; $i++) { 更改为 for($i=1; $i&lt;=$diceCount; $i++) {
猜你喜欢
  • 1970-01-01
  • 2021-06-02
  • 2017-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-04
  • 1970-01-01
相关资源
最近更新 更多