【问题标题】:6 different random unique numbers php [duplicate]6个不同的随机唯一数字php [重复]
【发布时间】:2015-03-31 03:47:45
【问题描述】:

我使用rand() 函数在数组中生成了 6 个随机数。我想确保这些数字都不是重复的。 我写了:

$lucky_numbers = array (rand (1,50), rand (1,50),rand (1,50),rand (1,50),rand (1,50),rand (1,50));
if ($lucky_numbers[0] == $lucky_numbers[1]) {
  print "same";
  $lucky_numbers[1]++;
}
if ($lucky_numbers[1] > 50) {
  $lucky_numbers[1] = $lucky_numbers[1]- 6;
}

然后用类似的代码检查每个连续的数字。但是有些东西不起作用。有任何想法吗 ? 提前致谢。

【问题讨论】:

  • 创建一个从 1 到 50 的数组。然后使用array_rand() 从数组中随机选取 6 个元素。
  • @Barmar:如果有重复怎么办?我想要 10 个介于 1 和 5 之间的唯一随机数。
  • @AbraCadaver 如果您从 1 到 50 制作一个数组并对其进行随机播放...您认为如何存在重复项?
  • 你怎么能在 1 和 5 之间取 10 个唯一的数字?只有 5 个选项。
  • @Jon: 好点,我误读了,因为我喝了很多啤酒。现在是星期六。

标签: php random numbers unique


【解决方案1】:

只需使用shuffle 函数即可。

<?php
$numbers = range(1, 50);
shuffle($numbers);
for ($x=1;$x<=6;$x++){ 
  echo $numbers[$x] . "\n";
}
?>

见codepad example

【讨论】:

  • 您可能希望使用array_search 来节省一些内存,因为您不需要大量的唯一数字,这也可能更快。
  • faster 和 save_memory 仅适用于大量数据。除非我使用 sleep,否则使用 50 个键我无法让它变慢。
  • 我也不知道你在搜索什么。
  • 没错,但是在大型应用程序中像这样浪费内存最终会变得更慢,你总是需要想办法提高性能。 $lucky_numbers = []; for($i=0;$i
猜你喜欢
  • 2018-02-16
  • 2013-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多