Home Backend Development PHP Tutorial PHP generates multiple non-repeating random numbers example program_PHP tutorial

PHP generates multiple non-repeating random numbers example program_PHP tutorial

Jul 13, 2016 am 10:43 AM
php rand No use exist Multiple Example data generate of program repeat random random number

Generating random data in php can be achieved directly by using mt_rand. If we want to generate non-repeating random numbers, we can use the unique_rand function. Let me summarize the commonly used methods.

The code is as follows:

The code is as follows Copy code
 代码如下 复制代码

//range 是将1到100 列成一个数组
$numbers = range (1,100);
//shuffle 将数组顺序随即打乱
shuffle ($numbers);
//array_slice 取该数组中的某一段
$no=6;
$result = array_slice($numbers,0,$no);
for ($i=0;$i<$no;$i++){
echo $result[$i]."
";
}
print_r($result);
?>


//range 是将1到42 列成一个数组
$numbers = range (1,42);
//shuffle 将数组顺序随即打乱
shuffle ($numbers);
//array_slice 取该数组中的某一段
$result = array_slice($numbers,0,3);
print_r($result);

//range is to list 1 to 100 into an array
$numbers = range (1,100);
//shuffle will disrupt the order of the array
shuffle ($numbers);
//array_slice takes a certain segment of the array
$no=6;
$result = array_slice($numbers,0,$no);
for ($i=0;$i<$no;$i++){
echo $result[$i]."
";
}
print_r($result);
?>


//range is to list 1 to 42 into an array
$numbers = range (1,42);
//shuffle will disrupt the order of the array
shuffle ($numbers);
//array_slice takes a certain segment of the array
$result = array_slice($numbers,0,3);
print_r($result);
 代码如下 复制代码

$numbers = range (1,20);
srand ((float)microtime()*1000000);
shuffle ($numbers);
while (list (, $number) = each ($numbers)) {
echo "$number ";
}
?>

Method 2

The code is as follows Copy code

$numbers = range (1,20);
srand ((float)microtime()*1000000);
shuffle ($numbers);
while (list (, $number) = each ($numbers)) {
echo "$number ";
}
?>

 代码如下 复制代码

function NoRand($begin=0,$end=20,$limit=5){
$rand_array=range($begin,$end);
shuffle($rand_array);//调用现成的数组随机排列函数
return array_slice($rand_array,0,$limit);//截取前$limit个
}
print_r(NoRand());
?>

Method 3

Use PHP to randomly generate 5 unique values ​​between 1-20. How to do it
 代码如下 复制代码

$tmp=array();
while(count($tmp)<5){
$tmp[]=mt_rand(1,20);
$tmp=array_unique($tmp);
}
print join(',',$tmp);
?>

The code is as follows Copy code
function NoRand($begin=0,$end=20,$limit=5){
$rand_array=range($begin,$end);
shuffle($rand_array);//Call the ready-made array random arrangement function
return array_slice($rand_array,0,$limit); //Intercept the first $limit items
}
print_r(NoRand());
?>
Or if you don’t shuffle
The code is as follows Copy code
$tmp=array();
while(count($tmp)<5){
$tmp[]=mt_rand(1,20);
$tmp=array_unique($tmp);
}
print join(',',$tmp);
?>

The above is all talk on paper, now comes the reality. The requirements are as follows

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?

Of course, report the situation to your superiors. But what we are discussing here is technology, which requires generating 16 non-repeating random numbers between 1-25 to fill in. 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 code is as follows Copy code
 代码如下 复制代码

/*
* 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 = '';
for($i=0; $i < count($arr);$i++)
{
$result .= $arr[$i].',';
}
$result = substr($result, 0, -1);
echo $result;
?>

程序运行如下:

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

/* * array unique_rand( int $min, int $max, int $num ) * Generate a certain number of non-repeating random numbers

* $min and $max: specify the range of random numbers

* $num: Specify the generated quantity
*/

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;
代码如下 复制代码

Array (
[0] => 0
 [1] => 1
 [2] => 2
 [3] => 3
 [4] => 4
 [5] => 5
 [6] => 6
 [7] => 7
 [8] => 8
 [9] => 9
 [10] => a
 [11] => b
 [12] => c
 [13] => d
 [14] => e
 [15] => f
 [16] => g
 [17] => h
 [18] => i
 [19] => j
 [20] => k
 [21] => l
 [22] => m
 [23] => n
 [24] => o
 [25] => p
 [26] => q
 [27] => r
 [28] => s
 [29] => t
 [30] => u
 [31] => v
 [32] => w
 [33] => x
 [34] => y
 [35] => z
)

} $arr = unique_rand(1, 25, 16); sort($arr); $result = ''; for($i=0; $i < count($arr);$i++)<🎜> {<🎜> $result .= $arr[$i].',';<🎜> }<🎜> $result = substr($result, 0, -1);<🎜> echo $result;<🎜> ?> The program runs as follows: 1 2,3,4,6,7,8,9,10,11,12,13,16,20,21,22,24 A few additional notes: •The mt_rand() function is used to generate random numbers. This function generates random numbers four times faster on average than rand(). •When removing duplicate values ​​from an array, the "flip method" is used, which is to use array_flip() to exchange the key and value of the array twice. This approach is much faster than using array_unique(). •Before returning the array, first use shuffle() to assign new key names to the array, ensuring that the key names are consecutive numbers from 0-n. If this step is not performed, the key names may be discontinuous when deleting duplicate values, causing trouble in traversal. Look at another example Generate one of the 36 characters 0-z. Each call to the getOptions() method generates a character, which is stored as follows: array[0] = 0, array[1] = 1, …, array[35] = z.
The code is as follows Copy code
Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 [10] => a [11] => b [12] => c [13] => d [14] => e [15] => f [16] => g [17] => h [18] => i [19] => j [20] => k [21] => l [22] => m [23] => n [24] => o [25] => p [26] => q [27] => r [28] => s [29] => t [30] => u [31] => v [32] => w [33] => x [34] => y [35] => z )

Then randomly generate a number between 0-35 as the index, which is actually to randomly pick out a number from the above array as the first character in the variable $result. This random index will then be assigned as the last one in the array, and it will not participate in the next round of random selection.

The code is as follows
 代码如下 复制代码

// 生成0123456789abcdefghijklmnopqrstuvwxyz中的一个字符
function getOptions()
{
$options = array();
$result = array();
for($i=48; $i<=57; $i++)
{
array_push($options,chr($i));
}
for($i=65; $i<=90; $i++)
{
$j = 32;
$small = $i + $j;
array_push($options,chr($small));
}
return $options;
}
/*
$e = getOptions();
for($j=0; $j<150; $j++)
{
echo $e[$j];
}
*/
$len = 10;
// 随机生成数组索引,从而实现随机数
for($j=0; $j<100; $j++)
{
$result = "";
$options = getOptions();
$lastIndex = 35;
while (strlen($result)<$len)
{
// 从0到35中随机取一个作为索引
$index = rand(0,$lastIndex);
// 将随机数赋给变量 $chr
$chr = $options[$index];
// 随机数作为 $result 的一部分
$result .= $chr;
$lastIndex = $lastIndex-1;
// 最后一个索引将不会参与下一次随机抽奖
$options[$index] = $options[$lastIndex];
}
echo $result."n";
}
?>

Copy code
// Generate a character in 0123456789abcdefghijklmnopqrstuvwxyz
function getOptions()
{
$options = array();
$result = array();
for($i=48; $i<=57; $i++)
{
        array_push($options,chr($i)); 
}
for($i=65; $i<=90; $i++)
{
$j = 32;
        $small = $i + $j;
        array_push($options,chr($small));
}
return $options;
}
/*
$e = getOptions();
for($j=0; $j<150; $j++)
{
echo $e[$j];
}
*/
$len = 10;
// Randomly generate array index to achieve random numbers
for($j=0; $j<100; $j++)
{
$result = "";
$options = getOptions();
$lastIndex = 35;
while (strlen($result)<$len)
{
// Randomly pick one from 0 to 35 as the index
$index = rand(0,$lastIndex);
//Assign random number to variable $chr
$chr = $options[$index];
// Random number as part of $result
$result .= $chr;
$lastIndex = $lastIndex-1;
//The last index will not participate in the next random draw
$options[$index] = $options[$lastIndex];
}
echo $result."n";
}
?>

http://www.bkjia.com/PHPjc/633165.htmlwww.bkjia.comtrue
http: //www.bkjia.com/PHPjc/633165.html
TechArticle
Generating random data in php can be achieved directly using mt_rand. If we want to generate non-repeating random numbers, we can use unique_rand function, let me summarize the commonly used methods. ...
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles