note 39506 added to function.shuffle

From: Date: Fri, 30 Jan 2004 20:03:52 +0000
Subject: note 39506 added to function.shuffle
Groups: php.notes 
Request: Send a blank email to php-notes+get-64457@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+39506 Delete -- http://master.php.net/manage/user-notes.php?action=delete+39506&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+39506&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#64457) next »