note 56146 deleted from function.rand by felipe
| From: | felipe@php.net | Date: | Sun, 30 Dec 2007 18:43:51 +0000 |
| Subject: | note 56146 deleted from function.rand by felipe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-134426@lists.php.net to get a copy of this message | ||
Note Submitter: Pierre C.
----
I am sorry to tell you this, mark at mmpro dot de, but the function you mentioned looks awfully and
unnecessarily slow to me:
At each iteration, you have to check if the generated number is not already in the list, so you end
up with a complexity of O(n²)... at best! (In the worst case, the algorithm might just run
forever!!!)
----
Here is a better (and safer!) way to generate a random array of different numbers:
- First generate an array, each element filled with a different value (like: 1,2,3,4,5,...,n)
- Then shuffle your array. In other words, swap each element in your array with another
randomly-chosen element in the array.
Now the algorithm has a complexity of O(n), instead of the original O(n²).
----
The generation of the array of values is left at the discretion of the programmer (it is down to
his/her needs to determine how the values should be reparted).
The shuffling of the array should go like this (WARNING: CODE NOT TESTED !!!):
$length = count($array) ;
for($i=0; $i<$length; $i++) {
// Choosing an element at random
$randpos = rand(0, $length-1) ;
// Swapping elements
$temp = $array[$randpos] ;
$array[$randpos] = $array[$i] ;
$array[$i] = $temp ;
}
return $array ;