Last active
August 29, 2015 14:03
-
-
Save fcaravana/eae0e9722b01c21cb9ac to your computer and use it in GitHub Desktop.
weight calculator
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 | |
/** | |
* From a list of items with priorities gets one based on their priority. | |
*/ | |
class PriorityCalculator | |
{ | |
public var $data = array(); | |
public var $universe = 0; | |
public function add($data, $probability) { | |
$this->data[$x = sizeof($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