php - Distribute associative array elements into groups with a maximum sum per group

233

I need to split my associative array into bunches of not greater than 50 in each bunch. Multiple elements may be pushed into a given group to ensure that a group reaches 50 before starting a new group.

Sample input:

$array = [
    '5' => 142,
    '2' => 57,
    '18' => 37
];

Desired result:

[
    ['5' => 50],
    ['5' => 50],
    ['5' => 42, '2' => 8],
    ['2' => 49, '18' => 1],
    ['18' => 36],
];
7

Answer

Solution:

just mind games

$line = [];
// Invert array
foreach($arr as $k=>$v) {
   $line = array_merge($line, array_fill(0, $v, $k));
}
// Split and count occurrences
$res = array_map('array_count_values', array_chunk($line, 50));
print_r($res);

947

Answer

Solution:

You could try something like this :

$total = [] ; $ckey = 0 ; 
foreach ($array as $key => $value) {
    while ($value) {
        $cursum = isset($total[$ckey]) ? array_sum($total[$ckey]) : 0 ;
        if ($cursum == 50) $ckey++ ;

        if ($value + $cursum > 50) $add = 50 - $cursum ;
        else  $add = $value ;

        $total[$ckey][$key] = $add ;
        $value -= $add ;
    }
}
print_r($total) ;

Outputs :

Array (
    [0] => Array (
            [5] => 50
        )

    [1] => Array (
            [5] => 50
        )

    [2] => Array (
            [5] => 42
            [2] => 8
        )

    [3] => Array (
            [2] => 49
            [18] => 1
        )

    [4] => Array (
            [18] => 36
        )
)

People are also looking for solutions to the problem: javascript - Sending the timing from the page load to the last occurrence of a button click?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.