Skip to content

Instantly share code, notes, and snippets.

@fcaravana
Last active August 29, 2015 14:03
Show Gist options
  • Save fcaravana/eae0e9722b01c21cb9ac to your computer and use it in GitHub Desktop.
Save fcaravana/eae0e9722b01c21cb9ac to your computer and use it in GitHub Desktop.
weight calculator
<?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