For example:

$groups = [ ['name' => 'Group 1', 'items' => [1]], ['name' => 'Group 2', 'items' => [1,2]], ['name' => 'Group 3', 'items' => [1,2,3,4,5,6]], ['name' => 'Group 4', 'items' => [1,2,3]], ['name' => 'Group 5', 'items' => [5,6]], ['name' => 'Group 6', 'items' => [5]], ]; 

Should be divided into arrays containing approximately the same number of elements. If in half, then:

 [ [ ['name' => 'Group 1', 'items' => [1]], ['name' => 'Group 2', 'items' => [1,2]], ['name' => 'Group 4', 'items' => [1,2,3]], ['name' => 'Group 5', 'items' => [5,6]], ], [ ['name' => 'Group 3', 'items' => [1,2,3,4,5,6]], ['name' => 'Group 6', 'items' => [5]], ] ]; 

This is useful when listing lists in columns (for example, menus), and it is necessary that no empty areas are formed.

  • ru.stackoverflow.com/questions/581668/… In short, the number of elements is the weight of the array. You need to find a combination that adds up to half the total weight. (well, or + -1 if the total weight is odd) - rjhdby
  • If in half, then - something figoenky in half turned out, in the first group of 8 elements, and in the second 6 ... - Akina
  • @Akina in the second 7. - GroZa
  • Well tady pal ... - Akina

1 answer 1

The classic backpack problem.

Since the domain does not necessarily require the optimal solution, you can try the greedy algorithm. Those. The vector of the number of elements in the array is sorted in descending order and begin to decompose into two (or more - depending on how many parts you need to divide) of the vector, putting the next element in the vector where the current amount is less.