note 39507 added to function.shuffle
| From: | BentonatGoatRiderdotcom at rn2 dot php dot net | Date: | Fri, 30 Jan 2004 20:05:13 +0000 |
| Subject: | note 39507 added to function.shuffle | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-64458@lists.php.net to get a copy of this message | ||
That implementation of Fisher-Yates is all messed up. First of all, what's this?
for ($i = count($array); --$i; $i > 0)
That abuses the "for" statement, swapping the increment and the comparison fields. It just
happens to work because --$i eventually hits 0.
Also, the mt_rand() should be (0, $i) not ($i+1), with $i+1 there's a 1 in N chance on the
first pass it shuffles in 1 past the end of the array, putting a blank at the last element.
Here's a fixed version. I swapped it around to go from small to big:
function fisherYatesShuffle(&$array)
{
for ($i = 0; $i<count($array); $i++)
{
$j = @mt_rand(0, $i+1);
$temp = $array[$i];
$array[$i] = $array[$j];
$array[$j] = $temp;
}
}
----
Manual Page -- http://www.php.net/manual/en/function.shuffle.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+39507
Delete -- http://master.php.net/manage/user-notes.php?action=delete+39507&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+39507&report=yes
Search -- http://master.php.net/manage/user-notes.php