Home >Backend Development >PHP Tutorial >指定范围内多个不重复随机数

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

WBOY
WBOYOriginal
2016-06-13 12:17:151073browse

求一个指定范围内多个不重复随机数~
例如500以内6个不重复数
又快又省最好了
谢谢高手了!
------解决思路----------------------

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


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

------解决思路----------------------
500个这么小的pool,完全可以用空间换时间。
<br />$arr = array();<br />for($i=1;$i<=500; $i++){<br />    array_push($arr, $i);<br />}<br /><br />shuffle($arr);<br />$ret = array_slice($arr, 0, 6);<br />print_r($ret);<br />

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