note 51147 added to function.shuffle

From: Date: Mon, 21 Mar 2005 22:10:25 +0000
Subject: note 51147 added to function.shuffle
Groups: php.notes 
Request: Send a blank email to php-notes+get-86760@lists.php.net to get a copy of this message
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.) 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; } } ---- Manual Page -- http://www.php.net/manual/en/function.shuffle.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+51147 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+51147&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+51147&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+51147&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+51147&report=yes&reason=useless Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+51147&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+51147&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#86760) next »