[ create a new paste ] login | about

Link: http://codepad.org/59wmsi4g    [ raw code | output | fork ]

PHP, pasted on Nov 18:
<?php

    $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

    var_dump($result);


Output:
array(3) {
  [0]=>
  array(3) {
    [0]=>
    int(8)
    [1]=>
    int(16)
    [2]=>
    int(8)
  }
  [1]=>
  array(4) {
    [0]=>
    int(8)
    [1]=>
    int(4)
    [2]=>
    int(4)
    [3]=>
    int(16)
  }
  [2]=>
  array(1) {
    [0]=>
    int(32)
  }
}


Create a new paste based on this one


Comments: