DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

ProbabilityRandom //PHP Class

08.20.2006
| 7496 views |
  • submit to reddit
        <a href="http://www.phpclasses.org/browse/package/1940.html">
Class to return items based on their probability.

Updated version can be found here</a>

usage
$prExample = new ProbabilityRandom;

$prExample->add( 'I have more chances than everybody :]', 30 );
$prExample->add( 'I have good chances', 10 );
$prExample->add( 'I\'m difficult to appear...', 1 );

for( $x=10; $x--; print $prExample->get() . '<br />' );

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com
class ProbabilityRandom {
	#private vars
	var
		$data = array(),
		$universe = 0;

	#add an item to the list and defines its probability of being chosen
	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 );
	}

	#remove an item from the list
	function remove( $index ){
		if( $index > -1 && $index < sizeof( $this->data ) ) {
			$item = array_splice( $this->data, $index, 1 );
			$this->universe -= $item->probability;
		}
	}

	#clears the class
	function clear(){
		$this->universe = sizeof( $this->data = array() );
	}

	#return a randomized item from the list
	function get(){
		if( !$this->universe )
			return null;
		$x = round( mt_rand( 0, $this->universe ) );
		$max = $i = 0;
		do
			$max += $this->data[ $i++ ]->probability;
		while( $x > $max );
		return $this->data[ $i-1 ]->value;
	}
}