'How to group array elements in order to have the minimum loss given a specific target number

I'm trying to understand how I should approach the following problem:

Given a specific array of float numbers, I must group them with the 2 following conditions:

a) Each group must not exceed a specific value.

b) The total "loss" remaining after the grouping must be the minimum possible.

So, for example let's say: array = [ 1.2 , 1.3 , 1.8 , 1.5 , 1 , 1.4 , 2.4 ]

Target number: 6

If the groups are:

a = ( 1.2 , 1.4 , 1.8 , 1.5 ) (sum = 5.9)

b = ( 1.3 , 1 , 2.4 ) (sum = 4.7)

Then the "loss" is (6 - 5.9) + (6 - 4.7 ) = 1.4

So the question is how can I find the groups that minimise this loss?

Extra information:

We have n groups, not just 2 and the numbers are always positive (meters more accurately). Also, no number in the array will ever exceed the target number. One thought I had is group them randomly and then make swaps between the groups but I cannot find the right conditions in order to achieve the 2nd condition.

Another example may be i.e

[2, 3.1, 2.8, 4, 2.2, 1.6, 1, 3.2]

in which case we need more than 2 groups.

Εssentially we are talking about aluminium frames that we want to cut in a way that will give the least possible alumni waste. The target number is the length of the alumni that we use for creating the frames and the frame lengths are the numbers in the array



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source