Skip to content

Instantly share code, notes, and snippets.

@Mezzle
Created February 16, 2012 23:51
Show Gist options
  • Save Mezzle/1848878 to your computer and use it in GitHub Desktop.
Save Mezzle/1848878 to your computer and use it in GitHub Desktop.
Pool Sampling
<?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