【问题标题】:maximum number of possibility最大可能性数
【发布时间】:2022-08-07 14:40:48
【问题描述】:

我需要从具有每种产品数量的数组中获得最大可能。 在计算可能性时,必须总是有两个产品,不能少也不能多。

// array products
$group_iten = array (1,1,4); // 6 units in 3 products

// max and min per product
$max_min_products = 2;

// my algorithm
$i = 0;
$c = 0;
$counter = 0;
while ( true ) {
    // Sorts array in place by values in descending order
    rsort($group_iten);
    
    if ( $c < $max_min_products ) {
        
        $group_iten[$i] -= 1;
        
        $i++;
        $c++;
        $counter++;
    }
    else {
        $c = 0;
        $i = 0;
    }
    
    if ( min($group_iten) == 0 ) {
        unset($group_iten[$i]);
    }
    
    if ( count($group_iten) < $max_min_products )
        break;
}
print_r($counter);
// result = 2

line output:
Array sorted:
        4, 1, 1
        3, 1, 0 ( 1 )
        2, 0, 0 ( 2 )
End;
result = 2

But with example array = [4, 4, 2];
        4, 4, 2 ( inital array )
        3, 3, 2  ( 1 )
        2, 2, 2  ( 2 )
        1, 1, 2  ( 3 )
        1, 0, 1  ( 4 )
        0,  , 0  ( 5 )

预期:结果 5,但我的算法结果为 8。

    标签: php arrays loops while-loop


    【解决方案1】:
    // specific category of required products
    $required_products = 2; // 2 types
    
    // array list base mysql query 
    $group_iten = array (4,4,2);
    
    // order by descending, fix possible ORDER ASC. 
    rsort($group_iten);
    
    // possibility number counter
    $i=0;
    
    // if the number of items in the group is greater than the required amount of product
    if ( count( $group_iten ) >= $required_products ) {
        
        // while the required quantity of item is greater than zero
        while ( $group_iten[$required_products-1] > 0 ) {
            
            // subtract from all possibility
            for ( $j = 0; $j <= ($required_products-1); $j++ )
                $group_iten[$j]--;
            
            // array order by desc
            rsort($group_iten);
            
            // count possibility
            $i++;
        }
    }
    echo  $i;
    
    output : 5
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    • 附加信息:算法评论
    猜你喜欢
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    相关资源
    最近更新 更多