note 79030 deleted from function.rand by felipe

From: Date: Sun, 30 Dec 2007 18:47:09 +0000
Subject: note 79030 deleted from function.rand by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-134461@lists.php.net to get a copy of this message
Note Submitter: ioann dot tschaikowsky at gmail dot com ---- This function generates unique random integers between $min and $max, resets history when new limits are requested or when there are no more numbers to return, never ever hangs or fails, never ever eats more memory than expected. This solution uses static variables in a function, stores previous limits and when those are changed or possible results are exhausted, generates a new list of possible results, then shuffles it and pops one number for each consequent call. PROS: Runs as fast as light when extracting a number, first call time with new limits depends on range size (don't know internal complexity of shuffle()). CONS: Might be quite slow initially with a big range, so probably it is best suited for little ones, and uses static variables so somebody could say "bleah"... but i just can't think a cleaner way to get this done. <?php function unirand($min, $max) { static $s_min = -1; static $s_max = -1; static $s_nums = array(); // if we have new limits if($s_min != $min || $s_max != $max || !count($s_nums)) { // init limits $s_min = $min; $s_max = $max; // create extractions $s_nums = range($s_min, $s_max); shuffle($s_nums); } // return next number return array_pop($s_nums); } ?>

« previous php.notes (#134461) next »