note 54924 deleted from function.shuffle by bjori

From: Date: Tue, 06 Jun 2006 21:34:37 +0000
Subject: note 54924 deleted from function.shuffle by bjori
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-113383@lists.php.net to get a copy of this message
Note Submitter: colin dot spamless dot mcewan at gmail dot com ---- 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.

« previous php.notes (#113383) next »