开发者

Array divide/split by value

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

With an array like the one above is there a way so I can divide/split the array based on the value suming up to a set value. e.g if I wanted them to equal 32. My final array will have upt开发者_开发知识库o 100 values all being either 32, 16, 8 or 4 and I just need to group the items so the value always equal a set amount so in this example its 32.

From the above array I would 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

as $a[0] sums up to 32 and so does $a[1] and $a[2].


$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 needed sum is a multiple of the biggest number (32).

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

Note: | means divides.


$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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜