Algorithm to split an array into P subarrays of balanced sum

前端 未结 10 1899
面向向阳花
面向向阳花 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:46

    I recently needed this and did as follows;

    1. create an initial sub-arrays array of length given sub arrays count. sub arrays should have a sum property too. ie [[sum:0],[sum:0]...[sum:0]]
    2. sort the main array descending.
    3. search for the sub-array with the smallest sum and insert one item from main array and increment the sub arrays sum property by the inserted item's value.
    4. repeat item 3 up until the end of main array is reached.
    5. return the initial array.

    This is the code in JS.

    function groupTasks(tasks,groupCount){
      var  sum = tasks.reduce((p,c) => p+c),
       initial = [...Array(groupCount)].map(sa => (sa = [], sa.sum = 0, sa));
      return tasks.sort((a,b) => b-a)
                  .reduce((groups,task) => { var group = groups.reduce((p,c) => p.sum < c.sum ? p : c);
                                             group.push(task);
                                             group.sum += task;
                                             return groups;
                                           },initial);
    }
    
    var tasks = [...Array(50)].map(_ => ~~(Math.random()*10)+1), // create an array of 100 random elements among 1 to 10
       result = groupTasks(tasks,7);                             // distribute them into 10 sub arrays with closest sums
    
    console.log("input array:", JSON.stringify(tasks));
    console.log(result.map(r=> [JSON.stringify(r),"sum: " + r.sum]));

提交回复
热议问题