Algorithm to split an array into P subarrays of balanced sum

前端 未结 10 1893
面向向阳花
面向向阳花 2020-12-08 05:00

I have an big array of length N, let\'s say something like:

2 4 6 7 6 3 3 3 4 3 4 4 4 3 3 1

I need to split this array into P subarrays (in

10条回答
  •  南笙
    南笙 (楼主)
    2020-12-08 05:43

    Working code below (I used php language). This code decides part quantity itself;

    $main = array(2,4,6,1,6,3,2,3,4,3,4,1,4,7,3,1,2,1,3,4,1,7,2,4,1,2,3,1,1,1,1,4,5,7,8,9,8,0);
    $pa=0;
    for($i=0;$i < count($main); $i++){
    $p[]= $main[$i];
    if(abs(15 - array_sum($p)) < abs(15 - (array_sum($p)+$main[$i+1])))
    {
    $pa=$pa+1;
    $pi[] = $i+1;
    $pc =  count($pi);
    
    $ba = $pi[$pc-2] ;
    
    $part[$pa] = array_slice( $main,  $ba, count($p));
    unset($p);
    }
    }
    print_r($part);
    for($s=1;$s';
    echo array_sum($part[$s]);
    }
    

    code will output part sums like as below

    13
    14
    16
    14
    15
    15
    17
    

提交回复
热议问题