note 71738 added to function.shuffle
| From: | VladimirKornea at osu1 dot php dot net | Date: | Wed, 13 Dec 2006 18:52:21 +0000 |
| Subject: | note 71738 added to function.shuffle | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-120588@lists.php.net to get a copy of this message | ||
While Markus' ass_array_shuffle() function is less memory intensive than my shuffle_me()
function, it is also approximately 40 times slower for an array containing 10,000 elements on
account of the repeated calls to the array_rand() function.
I originally submitted just the three lines of code of shuffle_me() that demonstrate the algorithm.
Since it has been posted as a function, I'm posting it here as the more robust and more aptly
named shuffle_assoc() function. It checks for errors and consumes less memory than shuffle_me(), but
is approximately 1.5 times as slow for an array containing 10,000 elements. For convenience,
I'm also pasting the original shuffle_me() and Markus' ass_array_shuffle() function.
<?
function shuffle_assoc($input_array) {
if(!is_array($input_array) or !count($input_array))
return null;
$randomized_keys = array_rand($input_array, count($input_array));
$output_array = array();
foreach($randomized_keys as $current_key) {
$output_array[$current_key] = $input_array[$current_key];
unset($input_array[$current_key]);
}
return $output_array;
}
?>
<?PHP
function ass_array_shuffle ($array) {
while (count($array) > 0) {
$val = array_rand($array);
$new_arr[$val] = $array[$val];
unset($array[$val]);
}
return $new_arr;
}
?>
<?php
function shuffle_me($shuffle_me) {
$randomized_keys = array_rand($shuffle_me, count($shuffle_me));
foreach($randomized_keys as $current_key) {
$shuffled_me[$current_key] = $shuffle_me[$current_key];
}
return $shuffled_me;
}
?>
----
Server IP: 64.71.164.2
Probable Submitter: 65.106.184.148
----
Manual Page -- http://www.php.net/manual/en/function.shuffle.php
Edit -- https://master.php.net/note/edit/71738
Del: integrated -- https://master.php.net/note/delete/71738/integrated
Del: useless -- https://master.php.net/note/delete/71738/useless
Del: bad code -- https://master.php.net/note/delete/71738/bad+code
Del: spam -- https://master.php.net/note/delete/71738/spam
Del: non-english -- https://master.php.net/note/delete/71738/non-english
Del: in docs -- https://master.php.net/note/delete/71738/in+docs
Del: other reasons-- https://master.php.net/note/delete/71738
Reject -- https://master.php.net/note/reject/71738
Search -- https://master.php.net/manage/user-notes.php