Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP权重算法_Php_Algorithm_Math_Php4 - Fatal编程技术网

PHP权重算法

PHP权重算法,php,algorithm,math,php4,Php,Algorithm,Math,Php4,我想知道这是否是一个充分的算法,用于寻找加权系统的最佳值。有什么可以补充的吗 在本例中,我希望$object->get()返回test4的概率比返回test1的概率大4倍 class weightCalculator { var $data = array(); var $universe = 0; function add( $data, $probability ){ $this->data[ $x = sizeof( $this->

我想知道这是否是一个充分的算法,用于寻找加权系统的最佳值。有什么可以补充的吗

在本例中,我希望
$object->get()
返回test4的概率比返回test1的概率大4倍

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 ); 

看起来很公平,这取决于使用情况。如果您需要
get()
方法具有更好的性能,您可以在
add()
方法中构建范围值,并使用二分法。

详细说明streetpc的答案;在数据数组旁边,使用
add()
维护一个大小相同的键数组,在其中存储范围的上限;例如,该数组看起来像{10,30,60,100}。(或者,使用一个包含同时包含数据和键的对象或结构的数组。)然后,您的
get()
方法只是在排序列表中搜索大于
$x
的第一个元素;二进制搜索可以在O(ln)中实现这一点,而在方法中是O(N)。您会占用一些额外的内存,但对于大多数应用程序来说,这似乎是一个很好的折衷办法。

您所说的“最佳值”是什么意思?随机变量$x的赋值,基于->宇宙中所有数据项的有序权重?我想我想知道我使用的方法是否是计算结果权重值的最佳方法。问一个愚蠢的问题,但你想在这里做什么?传递值,带权重,让它返回给我一个结果因子,其中包括我传入的值的权重。Cheers在本例中,您希望$object->get()返回test4的概率比返回test1的概率大4倍吗?