PHP Unique Random Numbers

匿名 (未验证) 提交于 2019-12-03 02:28:01

问题:

What would be a good way to generate 7 unique random numbers between 1 and 10. I can't have any duplicates. I could write a chunk of PHP to do this (using rand() and pushing used numbers onto an array) but there must be a quick way to do it.

any advice would be great.

回答1:

Simple one-liner:

print_r(array_rand(array_fill(1, 10, true), 7)); 


回答2:

  • Create an array from 1 to 10 (range).
  • Put it in random order (shuffle).
  • Select 7 items from the array (array_slice)


回答3:

Populate an array with ten elements (the numbers one through ten), shuffle the array, and remove the first (or last) three elements.



回答4:

Check out the comments in the php manual, there are several solutions for this.

An easy one is this one:

$min = 1; $max = 10; $total = 7; $rand = array(); while (count($rand) < $total ) {     $r = mt_rand($min,$max);     if (!in_array($r,$rand)) $rand[] = $r; } 


回答5:

Whole numbers? Well, if you want 7 out of 10 then you more efficiently DON'T want 3 out of 10.

Feel free to use any of the other responses but instead of creating 7 numbers start with 10 and eliminate 3. That will tend to speed things up by more than double.



回答6:

An implementation of Sjoerd's answer:

$ar = range(1, 10); shuffle($ar); $ar = array_slice($ar, 0, 7); 


回答7:

The "shuffle" method has a MAJOR FALW. When the numbers are big, shuffle 3 billion indexs will instantly CAUSE 500 error. Here comes a best solution for really big numbers.

function getRandomNumbers($min, $max, $total) {     $temp_arr = array();     while(sizeof($temp_arr) < $total) $temp_arr[rand($min, $max)] = true;     return $temp_arr; } 

Say I want to get 10 unique random numbers from 1 billion to 4 billion.

$random_numbers = getRandomNumbers(1000000000,4000000000,10); 

PS: Execution time: 0.027 microseconds



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!