note 54924 added to function.shuffle
| From: | colin dot spamless dot mcewan at gmail dot com | Date: | Tue, 19 Jul 2005 19:26:49 +0000 |
| Subject: | note 54924 added to function.shuffle | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-92183@lists.php.net to get a copy of this message | ||
Benton, Justin:
Your updated Fisher-Yates implementations with forward traversal order miss a rather important
point; in changing the order of traversal, you must also change the range of the array from which
you select the element with which to swap element i. Fisher-Yates partitions the initial data set
into a 'shuffled' and 'unshuffled' region, selecting randomly from the
'unshuffled' set to build a shuffled set.
To maintain this, you should assign $j = mt_rand($i, count($items-1)). (Assuming 'count'
is the appropriate idiom in PHP. I'm not a PHP person). You'll then doubtless want to pull
the 'count' call outside the loop, too.
Note that the random range *includes* $i. If it didn't, it'd be impossible for an element
to appear in the same position in the output as it appeared in the input, making a two-element array
'shuffle' deterministic.
With the code, as written drawing from the random range [0, $i], the shuffle will exhibit a bias for
elements appearing early in the input array to remain early in the output.
----
Manual Page -- http://www.php.net/manual/en/function.shuffle.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+54924
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+54924&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+54924&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+54924&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+54924&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+54924&report=yes&reason=non-english
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+54924&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+54924&report=yes
Search -- http://master.php.net/manage/user-notes.php