-
-
Save miguelramos/06630796c888aec72da7 to your computer and use it in GitHub Desktop.
Random probability by weight.
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 | |
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