I have a parts list with 1000 rows. The two fields are “Part Number” and “Cost”. The costs range from $1 to $2000 (integers all).
- A034, 1
- A012, 5
- A084, 10
- B309, 13
- A094, 25
- A370, 50
- A233, 75
- A343, 75
- C124, 78
- …
- D239, 500
- …
- X998, 1980
- Z901, 2000
I want to create a list of all combinations of parts whose combined cost falls within a tight range (the gap of the range will never be more than $50). For example, given a range of $70-75, the returned list would be:
- A343 (total $75)
- A233 (total $75)
- A370, A094 (total $75)
- A370, B309, A084 (total $73)
- A370, B309, A084, A034 (total $74)
My first thoughts were to iterate through all possible combinations of parts that could meet the criteria (i.e. <= the upper number of the range) and report those combinations whose sums fell within the range. It quickly became obvious that would fail because the number of combinations becomes astronomical pretty quickly. But given that most combinations would not meet the criteria, is this problem reasonably solvable?
Given that the data is in a table in a MySQL database, my preferred solution would be some SQL or Stored Proc, next preferred PHP, finally Javascript.
(ETA: the missed hit discovered by @piotrm)
You have to limit maximum of total cost, or the number of combinations will go up to the sky no matter how you try to find them. In the following example it is limited to 75, but you may try other values to see it you can still find results in a reasonable time.
You can also adapt this solution to update combinations table on inserts or updates for your main table, letting you get results extremely quick for any range that doesnt exceed your set limit (but slowing inserts obviously as it’s where all the work is done).
Create tables and trigger:
Then populate using:
or (as test data)
And finally get your result using:
You may put any range here with maximum less than 75 (or whatever you set as limit in the table creation part and trigger).
Results: