Home  >  Article  >  Backend Development  >  求一个指定范围内多个不重复随机数~

求一个指定范围内多个不重复随机数~

WBOY
WBOYOriginal
2016-06-23 13:37:33788browse

例如500以内6个不重复数
又快又省最好了
谢谢高手了!


回复讨论(解决方案)

for($i=0; $i<6; $i++)  echo rand(1, 500), PHP_EOL;
绝不重复,不信你试

用arrayfille做一个1-500的数组
shuffle洗牌,arrayslice取前6个

for($i=0; $i<6; $i++)  echo rand(1, 500), PHP_EOL;
绝不重复,不信你试


274 335 220 220 350 215 

是不是该买彩票呢?

<?php function unique_random(& $result, $size=6, $min=0, $max=500){    $num = mt_rand($min, $max);    !in_array($num, $result) && array_push($result, $num);        return count($result) >= $size ? $result : unique_random($result, $size, $min, $max);}$result = array();unique_random($result);print_r($result);


Array(    [0] => 132    [1] => 351    [2] => 43    [3] => 425    [4] => 449    [5] => 269)

500个这么小的pool,完全可以用空间换时间。

$arr = array();for($i=1;$i<=500; $i++){    array_push($arr, $i);}shuffle($arr);$ret = array_slice($arr, 0, 6);print_r($ret);

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