Created
February 16, 2012 23:51
-
-
Save Mezzle/1848878 to your computer and use it in GitHub Desktop.
Pool Sampling
This file contains 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 | |
class PoolSample | |
{ | |
private $_pool = array() | |
/** | |
* Constructor | |
* | |
* @param Array The Pool to Sample - Zero Indexed Array | |
* | |
* @return void | |
*/ | |
public function __construct($pool) | |
{ | |
$this->_pool = $pool; | |
} | |
/** | |
* Sampling Function | |
* | |
* @param int Amount of items to return | |
* | |
* @return Array Random Sample of Pool | |
*/ | |
public function sample($sample_size) | |
{ | |
$sample = array(); | |
foreach ($$this->_pool AS $k => $v) | |
{ | |
if ($k < $sample_size) | |
{ | |
$sample[] = $v; | |
} | |
elseif ($this->_random_float() < $sample_size / ($k + 1)) | |
{ | |
$replace = rand(0, count($sample) -1); | |
$sample[$replace] = $v; | |
} | |
} | |
return $sample; | |
} | |
/** | |
* Get a random float between 0 and 1 | |
* | |
* @return float Random float between 0 and 1 | |
*/ | |
private function _random_float() | |
{ | |
return rand(0, getrandmax())/getrandmax(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment