Skip to content

Instantly share code, notes, and snippets.

@miguelramos
Forked from fcaravana/PriorityCalculator.php
Last active August 29, 2015 14:03
Show Gist options
  • Save miguelramos/06630796c888aec72da7 to your computer and use it in GitHub Desktop.
Save miguelramos/06630796c888aec72da7 to your computer and use it in GitHub Desktop.
Random probability by weight.
<?php
class PriorityCalculator
{
private $data = array();
private $universe = 0;
public function add( $data, $probability )
{
$this->data[ $x = count( $this->data ) ] = new stdClass;
$this->data[ $x ]->value = $data;
$this->universe += $this->data[ $x ]->probability = abs( $probability );
}
public function get()
{
if( !$this->universe )
{
return null;
}
$x = round( mt_rand( 0, $this->universe ) );
$max = 0;
$i = 0;
while( $x > $max )
{
$max += $this->data[ $i++ ]->probability;
}
$val=-1;
if($this->universe==1)
{
$val = $this->data[$i]->value;
}
else
{
$val = $this->data[$i-1]->value;
}
return $val;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment