在PHP中使用数组不重复的随机数 [英] Random Numbers without duplication using an array in PHP

查看:123
本文介绍了在PHP中使用数组不重复的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在PHP中创建一个随机数生成器.它应该一次生成三(3)个数字,而无需重复.也就是说,三个数字不能相同.

I'm trying to create a random number generator in PHP. It's supposed to generate three (3) numbers at a time, without repeat. That's to say, the 3 numbers cannot be the same.

这是我到目前为止尝试过的:

Here's what I've tried so far:

$array = [];

$A = mt_rand(1,36);
$array[0] = $A;

$B = mt_rand(1,36);
$array[1] = $B;

if(in_array($B,$array)){
    $B = mt_rand(1,36);
    $array[1] = $B;
}

$C = mt_rand(1,36);
$array[2] = $C;

if(in_array($C,$array)){
    $C = mt_rand(1,36);
    $array[2] = $C;
}

$length = count($array);

//display the array values;

for($i = 0; $i < $length; $i++){
    echo ($array[$i]."<br>");
}

谁能告诉我我要去哪里错了?

Can anyone tell me where I'm going wrong?

推荐答案

就像这样(根据我的最初评论),

Like this ( as per my initial comment ),

$array = [];

while( count($array) < 3 ){
    $rand = mt_rand(1,36);
    $array[$rand] = $rand;
}

print_r( $array );

通过将键"设置为随机数,我们可以滥用关联数组键是唯一的事实.然后,只需等到数组包含所需数量的唯一项,这很简单.

By setting the "key" to be the random number, we can abuse the fact that associative array keys are unique. Then it's a simple matter of waiting until the array contains the desired amount of unique items.

您可以在此处

输出:(您的结果可能会有所不同,这是随机的)

Outputs: ( your results may vary, it's random )

Array
(
    [16] => 16
    [20] => 20
    [27] => 27
)

更新,我正在尝试一种有效的方法,而不使用循环(在我下班回家的路上),这种方法在某些情况下甚至会更好.

UPDATE I was trying to think of a valid way to do it without using a loop ( on my way home from work ), and this way may be even better in some cases.

$a = range(1,36);

shuffle($a);

$array = array_slice($a, 0, 3);

print_r($array);

当您必须找到的项目数量更多时,这将具有更好的性能.这是因为没有重复,也没有碰撞.因此,如果您的交易范围较小,但需要查找许多退货项目,则可以更好地进行预成型.如果您有很多物品而只需要退货,那么第一个可能会更好,如果不是从速度上考虑,而是从内存使用上考虑.

This will have better performance when the number of items you must find is higher. This is because there is no repetition, no collisions. So if you have a small range but need to find many items for the return, this will preform better. If you have many items and need to return only few, then the first one may be better, if not from speed then from memory use.

您可以在此处

此参考使用

range()-创建一个包含一系列元素的数组.

range() - Create an array containing a range of elements.

http://php.net/manual/en/function.range.php

shuffle()-随机排列(随机化数组中的元素的顺序).它使用了不适合加密目的的伪随机数生成器.

shuffle() - Shuffles (randomizes the order of the elements in) an array. It uses a pseudo random number generator that is not suitable for cryptographic purposes.

http://php.net/manual/en/function.shuffle.php

array_slice()-从数组中返回由offset和length参数指定的元素序列.

array_slice() - Returns the sequence of elements from the array as specified by the offset and length parameters.

http://php.net/manual/en/function.array -slice.php

所以最后解释一下

  • 首先,我们创建一个包含每个可能数字作为元素的数组.例如这样的[1,2,3,4,5,6, ...].
  • 接下来,我们对其进行混洗,从而使整个数组的顺序随机化. Shuffle通过引用"修改了数组,因此它不返回我们的数组,因此没有赋值(我认为它返回布尔值,但是我对如何失败并返回false感到迷惑,几乎只是返回true,我们不想用)覆盖数组.这样我们的示例就变成了[16,20,27,14,5,1, ...]
  • 最后,我们减少了需要退货的物品数量.最后,我们以[16,20,27];
  • 结尾
  • First we create an array that contains each of our possible numbers as an element. So for example like this [1,2,3,4,5,6, ...].
  • Next we shuffle it which randomizes the order of the whole array. Shuffle modifies the array by "reference" so it doesn't return our array and therefor there is no assignment ( I think it returns Boolean, however I'm at a loss as to how it could fail and return false, pretty much it just returns true which we don't want to overwrite our array with ). So our example then becomes this [16,20,27,14,5,1, ...]
  • Last we cut out the number of items we need to return. Finally we end the example with this [16,20,27];

通过在循环条件下分配$rand变量的值,可以将第一行压缩为一行(实际上为2行).像这样:

You can crunch the first one down into one ( really 2) line by assigning the value of the $rand variable in the condition of the loop. Like this:

$array = [];

while( count($array) < 3 && false !== ($rand = mt_rand(1,36))) $array[$rand] = $rand;

因为mt_rand(1,36)永远不会返回布尔值false.另外,如果我记得mt_rand现在与rand相同,或者至少在当前的PHP版本中是相同的.

Because mt_rand(1,36) will never return boolan false. Also if I remember mt_rand is the same as rand now, or at least in current PHP versions.

注意:从PHP 7.1.0开始,rand()使用与mt_rand()相同的随机数生成器.为了保持向后兼容性,rand()允许max小于min,而不是将FALSE作为mt_rand()返回. http://php.net/manual/zh/function.rand.php

希望它能对您有所帮助,记住要跳出思维框.

Hope it helps you, remember to think outside of the box.

这篇关于在PHP中使用数组不重复的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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