note 79030 added to function.rand
| From: | ioann dot tschaikowsky at gmail dot com | Date: | Wed, 07 Nov 2007 19:03:28 +0000 |
| Subject: | note 79030 added to function.rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-132085@lists.php.net to get a copy of this message | ||
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);
}
?>
----
Server IP: 213.92.11.19
Probable Submitter: 212.112.241.44
----
Manual Page -- http://www.php.net/manual/en/function.rand.php
Edit -- https://master.php.net/note/edit/79030
Del: integrated -- https://master.php.net/note/delete/79030/integrated
Del: useless -- https://master.php.net/note/delete/79030/useless
Del: bad code -- https://master.php.net/note/delete/79030/bad+code
Del: spam -- https://master.php.net/note/delete/79030/spam
Del: non-english -- https://master.php.net/note/delete/79030/non-english
Del: in docs -- https://master.php.net/note/delete/79030/in+docs
Del: other reasons-- https://master.php.net/note/delete/79030
Reject -- https://master.php.net/note/reject/79030
Search -- https://master.php.net/manage/user-notes.php