note 39506 deleted from function.shuffle by tomsommer
| From: | tomsommer@php.net | Date: | Fri, 30 Jan 2004 21:57:07 +0000 |
| Subject: | note 39506 deleted from function.shuffle by tomsommer | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-64459@lists.php.net to get a copy of this message | ||
Note Submitter: Benton at GoatRider dot com
----
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;
}
}