Home > other >  maximum number of possibility
maximum number of possibility

Time:07-29

I need to get the max possible from array that has the quantity of each product. In the calculation of possibilities, there must always be two products, it cannot be less or more.

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

Expected: result 5, but my algorithm result 8.

CodePudding user response:

// specific category of required products
$required_products = 2; // 2 types

// array list base mysql query 
$group_iten = array (4,2,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] > 0 ) {
        
        // subtract from the smallest column
        $group_iten[$required_products]--;
        
        // rearrange the array in descending order
        rsort($group_iten);
        
        // count possibility
        $i  ;            
    }
}

Output: 2 possibility
  • Related