Home > php教程 > php手册 > body text

PHP函数:生成N个不重复的随机数,php 随机数

WBOY
Release: 2016-06-13 09:29:53
Original
1094 people have browsed it

PHP函数:生成N个不重复的随机数,php 随机数

PHP函数:生成N个不重复的随机数

思路:将生成的随机数存入数组,再在数组中去除重复的值,即可生成一定数量的不重复随机数。

 

程序:

<?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

补充说明:

  1、生成随机数使用了mt_rand()函数,这个函数比rand()函数快4倍;

  2、去除数组重复值时采用了“翻翻法”,就是用array_flip()把数组的key和value交换两次。比用array_unique()快很多。

matlab怎产生不重复的随机数?

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

用excel生成N个随机数,怎用if函数使它不重复

选中A1:A1000,在编辑栏输入
=RAND()
按【CTRL+回车】
再选中B1:B1000,在编辑栏输入
=RANK(A1,a$1:A$1000)
按【CTRL+回车】
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!