search
HomeBackend DevelopmentPHP TutorialPHP 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
phprandNouseexistMultipleExampledatagenerateofprogramrepeatrandomrandom 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 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 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) $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) $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         $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 {
 $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           $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 { $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   {
      array_push($options,chr($i)); 
  }
  for($i=65; $i    {
       $j = 32;
       $small = $i + $j;
       array_push($options,chr($small));
 }
  return $options;
}
/*
$e = getOptions();
for($j=0; $j {
 echo $e[$j];
}
*/
$len = 10;
// 随机生成数组索引,从而实现随机数
for($j=0; $j {
  $result = "";
  $options = getOptions();
  $lastIndex = 35;
  while (strlen($result)   {
    // 从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 {
        array_push($options,chr($i)); 
}
for($i=65; $i {
$j = 32;
        $small = $i + $j;
        array_push($options,chr($small));
}
return $options;
}
/*
$e = getOptions();
for($j=0; $j {
echo $e[$j];
}
*/
$len = 10;
// Randomly generate array index to achieve random numbers
for($j=0; $j {
$result = "";
$options = getOptions();
$lastIndex = 35;
while (strlen($result) {
// 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
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
How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?Apr 23, 2025 am 12:16 AM

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

How can you optimize PHP session performance?How can you optimize PHP session performance?Apr 23, 2025 am 12:13 AM

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

What is the session.gc_maxlifetime configuration setting?What is the session.gc_maxlifetime configuration setting?Apr 23, 2025 am 12:10 AM

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

How do you configure the session name in PHP?How do you configure the session name in PHP?Apr 23, 2025 am 12:08 AM

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

How often should you regenerate session IDs?How often should you regenerate session IDs?Apr 23, 2025 am 12:03 AM

The session ID should be regenerated regularly at login, before sensitive operations, and every 30 minutes. 1. Regenerate the session ID when logging in to prevent session fixed attacks. 2. Regenerate before sensitive operations to improve safety. 3. Regular regeneration reduces long-term utilization risks, but the user experience needs to be weighed.

How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

See all articles

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version