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 ;
lmpx.com only provides a reader for public news (NNTP) servers. It is not
affiliated with the servers or forums shown here and is not responsible for
the content of articles, which is written by their respective authors.