note 56146 added to function.rand
| From: | PierreC dot at osu1 dot php dot net | Date: | Wed, 24 Aug 2005 23:27:07 +0000 |
| Subject: | note 56146 added to function.rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-94157@lists.php.net to get a copy of this message | ||
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 ;
----
Manual Page -- http://www.php.net/manual/en/function.rand.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+56146
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+56146&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+56146&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+56146&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+56146&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+56146&report=yes&reason=non-english
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+56146&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+56146&report=yes
Search -- http://master.php.net/manage/user-notes.php