顺序中的随机数+唯一的PHP


random numbers in order + unique php

我正在尝试创建一个具有以下功能的随机数生成器:

  • 每一个都是独一无二的
  • 数字为 1 或 49,介于两者之间
  • 从低到高排序

这就是我到目前为止所拥有的

$numbers = rand(1, 49)." ".rand(1, 49)." ".rand(1, 49)." ".rand(1, 49)." ".rand(1, 49)." ".rand(1, 49);
echo "Your Lucky Lotto Numbers Are: ".$numbers;

我只是不太确定如何订购它们,而且数字是唯一的。

只需创建一个包含从 1 到 49 的所有数字的数组,然后开始随机删除元素。仅保留所需的元素数量。这样,它们就已经井井有条了,绝对是独一无二的。

例:

$values = range(1,49);
while(count($values)>6) {
  unset($values[array_rand($values)]);
}
print "Your results: ".implode(', ',$values);
$numbers = range(1, 49);
shuffle($numbers);
$numbers = array_slice($numbers, 0, 5);
sort($numbers);
foreach ($i=0; $i<6; $i++) {
    echo $numbers[$i]." ";
}

范围和随机播放。

你应该为此使用一个数组:

$numbers = range(1, 49); //generate the array
shuffle($numbers); //shuffle the array
$numbers = array_slice($numbers, 0, 6); // cut the array in the appopriate length
echo "Your Lucky Lotto Numbers Are: ";
print_r(asort($numbers)); //sort and print

一些有用的文献:

  • PHP 中的数组:http://php.net/manual/en/language.types.array.php
  • 使用 foreach 遍历数组元素:http://php.net/manual/en/control-structures.foreach.php
  • 在 PHP 中排序:http://php.net/manual/en/array.sorting.php

取一个带有数字的数组,取 6 个随机数(或随机数组,选择前 6 个),对您选择的数字进行排序。效率不高,但绝对应该有效:

$numbers = range(1, 49);
shuffle($numbers);
$picks = array_slice($numbers, 0, 6);
sort($picks);

至少有 3 种方法可以做到这一点:

1) 生成不存在的数字

您创建数组并向其中添加随机数。如果新生成的数字已经在该数组中,则生成另一个(依此类推,直到它是唯一的,在某个 while 循环中检查它),然后对其进行排序。我会推荐这个

2) 所有现有较低数字的增量

对于每个新的随机数,您将最大值降低 1,然后在添加此数字时,为数组中的每个较小数字递增它

例如,当您有范围 1-49(含)和数字 [4、8、6、15] 时,您将生成 1-45(含)的数字,因为只剩下 45 个空闲数字。假设您生成了 8,这意味着 8ht 自由数,并且由于 4、8 和 6 已经存在,因此增加了三倍,而您得到了 11,但是这需要您的数组一直排序。

3)与@hexblot说的相同

我会选择 1,因为它很简单,如果数字数量比数字范围小"很多",你不会得到太多相同的选择(即 5-49 - 10% 的 10% 并不多)

也许有点

广泛,但这将为您提供 6 个唯一的排序数字

$arr = array();
while ( count($arr) < 6 ) {
    $x = mt_rand(1,49);
    if ( !in_array($x,$arr) ) {
        $arr[] = $x;
        asort($arr);
    }
}
foreach($arr as $x){
        echo $x." ";
        }