Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to check sum of numbers from several ranges wanted

Tags:

algorithm

i'd like to know if there is more optimal algorithm for the case below than simple iterating over the collection of items.

Suppose there are several items (2-10) with weight defined as range and increment, like
Item1 [0, 50] increment = 5
Item2 [40, 60] increment = 10.

The task is to check if there is at least one combination of weights which sum up to 100. In the example above there are 50+50 and 40+60 combinations.

As the number of items is not big iterating over all items weights wouldn't take much time but maybe there is a better way.

Thanks

UPDATE: i look for algorithm which doesn't require the list of all possible weights or weights sum, i need algorithm which checks if there is at least one combination of weights equals 100 just knowing the range and increment

like image 469
Melena Avatar asked Dec 26 '11 14:12

Melena


2 Answers

This problem seems to be a version of the subset sum problem, which is NP-complete. Hence the answer is no, there probably isn't an efficient algorithm in the general case. Some heuristics may help you achieve good results though.

like image 167
mitchus Avatar answered Oct 13 '22 10:10

mitchus


If I'm understanding this right, we're given some total T (with T=100 in this case), and k pairs of ranges and intervals

([x1,y1], n1), ([x2,y2], n2), ..., ([xk,yk], nk)

and for each of them we've got to pick a value

ai ∈ {xi, xi+ni, xi+2ni, ..., yi}

so that

a1 + a2 + ... + ak = T


So basically, the problem is to find values ci satisfying

x1+c1n1 + x2+c2n2 + ... + xk+cknk = T

subject to the constraints

0 ≤ ci ≤ (yi-xi)/ni for all i.


I believe this is what they call a linear integer constraint satisfaction problem. The general class of approaches for these kinds of problems is called integer linear programming. Such problems are usually NP-complete (though I don't know nearly enough to comment on this specific case), but I think there are still some relatively efficient heuristics.

In fact, this belongs to an even more specific subset of problems, as all the variables ci can only take a finite number of values (being integers, bounded above and below). Some Googling for CLP(FD) (constraint logic programming on finite domains) might give you an idea of how these are approached in general (though again, this may be a special case with an easier solution that I'm unaware of).

like image 35
Nick Barnes Avatar answered Oct 13 '22 12:10

Nick Barnes