2

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
  • Your method is probably fine. Using mt_rand() will speed things up a bit, though. Commented Oct 17, 2011 at 11:05

6 Answers 6

10
  • Create an array from 1 to 10 (range).
  • Put it in random order (shuffle).
  • Select 7 items from the array (array_slice)
Sign up to request clarification or add additional context in comments.

1 Comment

Instead of the second 2 steps, use array_rand(array, 7)
5

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

Comments

3

Simple one-liner:

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

4 Comments

I voted up this, but generated array is not random enough, the sequence of elements is regular !
@Masoud M. Do you have any reference? (just out of curiosity)
Check this out. It generates like: Array( [0] => 2 [1] => 4 [2] => 5 [3] => 6 [4] => 7 [5] => 9 [6] => 10 )
Ah you mean the result is sorted? Yes, that may be true, but not a real problem. One could shuffle the input/output array to get an unsorted result.
0

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

1 Comment

Not very efficient, but easy to comprehend.
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.