note 51147 modified in function.shuffle by danbrown
| From: | danbrown@php.net | Date: | Fri, 25 Jul 2008 17:44:16 +0000 |
| Subject: | note 51147 modified in function.shuffle by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-142715@lists.php.net to get a copy of this message | ||
[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;
}
}
?>
--was--
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;
}
}
http://php.net/manual/en/function.shuffle.php