Skip to content

Instantly share code, notes, and snippets.

@JoshuaEstes
Created January 10, 2013 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshuaEstes/4504202 to your computer and use it in GitHub Desktop.
Save JoshuaEstes/4504202 to your computer and use it in GitHub Desktop.
Select n random elements from N without replacement.
<?php
/**
* This function will take an array and select n from it
* without replacement. This can be used as a random number
* generator
*
* Example: I want to select $n numbers from a pool of $N numbers
* <code>
* $values = $srs(range(1,100), 5);
* </code>
* The above example will select 5 random numbers 1 to 100 without
* replacement
*
* Use case, lottery picking numbers, I'm sure there are others.'
*
* @param array $N
* @param integer $n
* @return array
*/
$srs = function(array $N, $n) {
$r = array();
for ($i = 0; $i < $n; $i++) {
$x = floor(count($N)*(hexdec(bin2hex(openssl_random_pseudo_bytes(4)))/0xffffffff));
$r[] = $N[$x];
unset($N[$x]);
$N = array_values($N);
}
return $r;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment