note 51147 deleted from function.shuffle by googleguy

From: Date: Tue, 22 Oct 2013 10:16:53 +0000
Subject: note 51147 deleted from function.shuffle by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-196972@lists.php.net to get a copy of this message
Note Submitter: monte at ohrt dot com ---- [EDIT by danbrown AT php DOT net: As pointed out on 25 July, 2008, by "Anonymous", this implementation may have some errors or inconsistencies that may cause this function not to achieve the desired result. "Anonymous" provided the following link for more information: http://en.wikipedia.org/wiki/Fisher-Yates_shuffle] This is an attempt to get the Fisher Yates shuffle right, and as optimized as possible. The array items are stepped through from last to first, each being swapped with another between itself and the beginning of the array (N-1 shuffles required.) Using list() to swap array vars instead of a tmp var proved to be slightly slower. Testing for $i = $j decreases performance as the array size increases, so it was left out (elements are always swapped.) <?php function fisherYatesShuffle(&$items) { for ($i = count($items) - 1; $i > 0; $i--) { $j = @mt_rand(0, $i); $tmp = $items[$i]; $items[$i] = $items[$j]; $items[$j] = $tmp; } } ?>

« previous php.notes (#196972) next »