note 79030 deleted from function.rand by felipe

[email protected]
Newsgroups php.notes
Message-ID <[email protected]>
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);
	}

?>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.