note 7632 added to shuffle

From: Date: Thu, 10 Aug 2000 02:15:44 +0000
Subject: note 7632 added to shuffle
Groups: php.notes 
Request: Send a blank email to php-notes+get-742@lists.php.net to get a copy of this message
As it has been previously stated, there are problems connected with using shuffle() if you use a solaris-based web-server. <BR>This is my case so I have (with a little help) made a Fisher Yates Shuffle routine as you might know it from "perldoc -q shuffle".<BR> Here it is: <P> // Fisher-Yates Shuffle an array in place (pass-by-reference)<BR> // Converted from "perldoc -q shuffle"<BR> function f_y_Shuffle(&$arr) {<BR> // Reverse a splice in an array (used by f_y_Shuffle()<BR> function reverse_splice(&$splice, $i1, $i2) {<BR> if($i1>$i2) { $swp = $i1; $i1 = $i2; $i2 = $swp; }<BR><BR> for($k=$i2;$k>=$i1;$k--){$tmpArr[] = $splice[$k];}<BR> for($k=0;$k<count($tmpArr);$k++) {$splice[$i1+$k] = $tmpArr[$k];}<BR> }<BR> $i = count($arr);<BR> mt_srand((double)microtime()*1000000);<BR> while($i>=0) {<BR> --$i;<BR> $j = @mt_rand(0, $i);<BR> if($i!=$j) {<BR> reverse_splice($arr, $i, $j);<BR> }<BR> }<BR> }<BR> <BR> Of course if you use PHP4, you could use array_splice() and array_reverse() instead of the "homemade" reverse_splice();<BR> <BR> Take a look at http://www.pert.dk/php/shuffletest.php3 <BR> TUI Per Thomsen,<BR> Omedia Digital<BR> http://dk.php.net/manual/function.shuffle.php

« previous php.notes (#742) next »