note 71738 deleted from function.shuffle by bobby

From: Date: Thu, 15 Feb 2007 22:50:25 +0000
Subject: note 71738 deleted from function.shuffle by bobby
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-123468@lists.php.net to get a copy of this message
Note Submitter: Vladimir Kornea ---- 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; } ?>

« previous php.notes (#123468) next »