Array Division / Value Division

$a = array(8, 16, 16, 32, 8, 8, 4, 4); 

With an array like above, there is a way so that I can split / split the array based on the value summing up to the given value. for example, if I wanted them to be 32. My last array will have up to 100 values, all of which will be 32, 16, 8 or 4, and I just need to group the elements so that the value always equals the set amount, so in this example its 32.

From the array above, I would hope to get:

 $a[0][1] = 16 $a[0][2] = 16 $a[1][3] = 32 $a[2][0] = 8 $a[2][4] = 8 $a[2][5] = 8 $a[2][6] = 4 $a[2][7] = 4 

since $ a [0] sums up to 32, and therefore $ a [1] and $ a [2].

+4
source share
3 answers
 $a = array(8, 16, 16, 32, 8, 8, 4, 4); $limit = 32; rsort($a); $b = array(array()); $index = 0; foreach($a as $i){ if($i+array_sum($b[$index]) > $limit){ $b[++$index] = array(); } $b[$index][] = $i; } $a = $b; print_r($a); 

It will work, but only because in your case you have 4 | 8 | 16 | 32, and only if the required amount is a multiple of the largest number (32).

Test: http://codepad.org/5j5nl3dT

Note: | means divides .

+4
source
 function split_into_thirtytwos($input_array) { $output_array=array(); $work_array=array(); $sum=0; sort($input_array,SORT_NUMERIC); while(count($input_array)>0) { $sum=array_sum($work_array)+$input_array[count($input_array)-1]; if($sum<=32) { $work_array[]=array_pop($input_array); } else { $output_array[]=$work_array; $work_array=array(); } } if(count($work_array)>0) {$output_array[]=$work_array;} return $output_array; } 

Tested with your input:

 Array ( [0] => Array ( [0] => 32 ) [1] => Array ( [0] => 16 [1] => 16 ) [2] => Array ( [0] => 8 [1] => 8 [2] => 8 [3] => 4 [4] => 4 ) ) 
0
source
 $a = array(8, 16, 16, 32, 8, 8, 4, 4); $group_limit = 32; $current_group = $result = array(); $cycles_since_successful_operation = 0; while ($a && $cycles_since_successful_operation < count($a)) { array_push($current_group,array_shift($a)); if (array_sum($current_group) > $group_limit) array_push($a,array_pop($current_group)); elseif (array_sum($current_group) < $group_limit) $cycles_since_successful_operation = 0; elseif (array_sum($current_group) == $group_limit) { $result []= $current_group; $current_group = array(); $cycles_since_successful_operation = 0; } } if ($a) $result []= $a; // Remaining elements form the last group 

http://codepad.org/59wmsi4g

0
source

All Articles