Home > Backend Development > PHP Problem > PHP generates 10 non-repeating random numbers

PHP generates 10 non-repeating random numbers

王林
Release: 2023-02-25 17:42:01
Original
7551 people have browsed it

PHP generates 10 non-repeating random numbers

Question:

There are 25 works for voting. You need to select 16 works in one vote. A single work can only be selected once in one vote. A programmer made a mistake earlier and forgot to store the votes in the database. The voting sequences generated by 200 users were empty. So how do you fill this gap?

It is necessary to generate 16 non-repeating random numbers between 1-25 to fill. How to design the function specifically? Store random numbers in an array, and then remove duplicate values ​​in the array to generate a certain number of non-repeating random numbers.

The program is as follows:

<?php
/*
* array unique_rand( int $min, int $max, int $num )
* 生成一定数量的不重复随机数
* $min 和 $max: 指定随机数的范围
* $num: 指定生成数量
*/
function unique_rand($min, $max, $num) {
  $count = 0;
  $return = array();
  while ($count < $num) {
      $return[] = mt_rand($min, $max);
      $return = array_flip(array_flip($return));
      $count = count($return);
  }
  shuffle($return);
  return $return;
}
$arr = unique_rand(1, 25, 16);
sort($arr);
$result = &#39;&#39;;
for($i=0; $i < count($arr);$i++)
{
  $result .= $arr[$i].&#39;,&#39;;
}
$result = substr($result, 0, -1);
echo $result;
?>
Copy after login

The running results are as follows:

2,3,4,6,7,8,9,10,11,12,13,16,20,21,22,24
Copy after login

Additional instructions:

1. The mt_rand() function is used to generate random numbers. This function generates random numbers four times faster on average than rand().

2. When removing duplicate values ​​from the array, the "flip method" is used, which is to use the array_flip() function to exchange the key and value of the array twice. This approach is much faster than using the array_unique() function.
3. Before returning the array, first use shuffle() to assign a new key name to the array, ensuring that the key name is a consecutive number from 0-n. If this step is not performed, the key names may be discontinuous when deleting duplicate values, causing trouble in traversal.

Recommended tutorial: PHP video tutorial

The above is the detailed content of PHP generates 10 non-repeating random numbers. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template