Heim  >  Artikel  >  Backend-Entwicklung  >  PHP函数:生成N个不重复的随机数,php 随机数_PHP教程

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

WBOY
WBOYOriginal
2016-07-13 10:24:091234Durchsuche

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;
}

补充说明:

  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+回车】

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/827776.htmlTechArticlePHP函数:生成N个不重复的随机数,php 随机数 PHP函数:生成N个不重复的随机数 思路:将生成的随机数存入数组,再在数组中去除重复的值...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn