I'm wondering if this is a sufficient algorithm for finding the best value with a weighted system. Is there anything I could add to make it better?
Edit:
in this example I would like the probability of $object->get() returning test4 to be 4 times greater than the probability of it returning test1 (thanks acrosman)
Thanks
class weightCalculator {
var $data = array();
var $universe = 0;
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 );
}
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;
}
}
$object = new weightCalculator;
$object->add( 'test1', 10 );
$object->add( 'test2', 20 );
$object->add( 'test3', 30 );
$object->add( 'test4', 40 );