Question

Does anyone know a function for probability distribution?

Say I have an array:

$arr = array(
    'A' => 100, 
    'B' => 200, 
    'C' => 300, 
    'D' => 400
);

I am looking for the function to output something like A=97, B=203,C=312,D=388 without having to do 1000 iterations. Any ideas?

No correct solution

OTHER TIPS

the array is $image, $Lg is the number of the discrete possible values

    $n_element=count($image);
    $cdf_array=array_fill(0,$Lg,0);
    for($i=0;$i<$n_element;$i++){
        $cdf_array[$image[$i]-1]=$cdf_array[$image[$i]-1]+1;
    }
    $cdf_array=array_filter($cdf_array,function($var){return $var!=0;});
    $keys=array_keys($cdf_array);
    $cdf_min=$cdf_array[$keys[0]];

    $not_null_el=count($keys);
    for($i=0;$i<$not_null_el;$i++){
        $cdf_array[$keys[$i]]=array_sum(array_chunk($cdf_array,$i+1,1)[0]);
        }
    }

Someone did this before. Follow the tut, it helped me out.

heres my take from it:

<?php
class WeightedRandom
{
    private $generated;
    private $weights;
    private $items;

    public function __construct( array $weights, array $items  )
    {

        $this->weights = $weights;
        $this->items = $items;

    }

    public function RandomNumber( int $min, int $max )
    {
        return mt_rand() * ( $max - $min ) + $max;
    }

    public function Generate()
    {
        $totalWeight = array_sum( $this->weights );
        $randomNum = $this->RandomNumber(0, $totalWeight);
        $weightSum = 0;
        $itemCount = count($this->items);
        $item;
        $i;

        for ( $i = 0; $i < $itemCount; $i++ ) 
        {
            $weightSum += $this->weights[$i];

            if ( $randomNum <= $weightSum )
            {
                $item = $this->items[$i];
                break;
            }
        }

        return $item;

    }

    /*
    public function Generate()
    {
        $weightedList = [];
        $multiples;
        $i;
        $j;
        $weightCount;

        for( $i = 0; $i < $weightCount; $i++ )
        {
            $multiples = $this->weights[$i] * 10;

            for( $j = 0; $j < $multiples; $j++)
            {
                array_push($weightedList, $this->items[$i]);
            }
        }

        return $weightedList;
    }
    */
}
?>

Source and tutorial

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top