Home > Backend Development > PHP Tutorial > PHP function: generate N non-repeating random numbers, php random numbers_PHP tutorial

PHP function: generate N non-repeating random numbers, php random numbers_PHP tutorial

WBOY
Release: 2016-07-13 10:24:09
Original
1314 people have browsed it

PHP function: generate N non-repeating random numbers, php random number

PHP function: generate N non-repeating random numbers

Idea: Store the generated random numbers in an array, and then remove duplicate values ​​from the array to generate a certain number of non-repeating random numbers.

Program:

<?php
/*
* array unique_rand( int $min, int $max, int $num )
* 生成一定数量的不重复随机数
* $min 和 $max: 指定随机数的范围
* $num: 指定生成数量
*/

function  unique_rand($min,$max,$num){
    $count = 0;
    $return_arr = array();
    while($count < $num){
        $return_arr[] = mt_rand($min,$max);
        $return_arr = array_flip(array_flip($return_arr));
        $count = count($return_arr);
    }
    shuffle($return_arr);
    return $return_arr;
}
Copy after login

Additional instructions:

1. The mt_rand() function is used to generate random numbers. This function is 4 times faster than the rand() function;

2. 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. Much faster than using array_unique().

How does matlab generate non-repeating random numbers?

rand(1,8)*100
ans =
Columns 1 through 7
81.4724 90.5792 12.6987 91.3376 63.2359 9.7540 27.849 8
Column 8
54.6882

Use excel to generate N random numbers. How to use the if function to make it non-repetitive

Select A1:A1000 and enter =RAND()
Press [CTRL+Enter]
Select B1:B1000, enter
=RANK(A1,a$1:A$1000) in the edit bar
Press [CTRL+Enter] 】

http://www.bkjia.com/PHPjc/827776.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/827776.htmlTechArticlePHP function: generate N non-repeating random numbers, php random number PHP function: generate N non-repeating random numbers Random number idea: store the generated random numbers in an array, and then remove duplicate values ​​in the array...
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