Created
January 10, 2013 17:51
-
-
Save JoshuaEstes/4504202 to your computer and use it in GitHub Desktop.
Select n random elements from N without replacement.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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