指定范围内, 指定个数,不重复随机数生成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
function runtime($mode = 0) {
static $t;
if(!$mode) {
$t = microtime();
return;
}
$t1 = microtime();
$arr_t0 = explode(" ",$t);
$arr_t1 = explode(" ",$t1);
return sprintf("%.3f ms",(array_sum($arr_t1)-array_sum($arr_t0))*1000);
}

$range['max'] = 100;
$range['min'] = 1;

runtime();
$arr_dict = range($range['min'],$range['max']);
echo runtime(1)."\n";

runtime();
list($first, $second) = array_rand($arr_dict,2);
echo runtime(2)."\n";

runtime();
shuffle($arr_dict);
echo runtime(3)."\n";

runtime();
mt_rand($range['min'],$range['max']);
echo runtime(4)."\n";

runtime();
$mt_rand_my = function ($start,$end,$count){
while($count){
$arr[] = mt_rand($start,$end);
if(count(array_unique($arr))>count($arr)) continue;
$count -- ;
}
return $arr;
};
$res = $mt_rand_my($range['min'],$range['max'],2);
echo runtime(5)."\n";

发现自己特别喜欢较真了,又变这样子 =_=

  • shuffle最优雅了(随机数量较多也可以考虑)
  • 不考虑重复情况的话,mt_rand最高效了
  • array_rand算是比较中庸么(1,2个随机数)