Reputation: 425291
I want to write a little helper utility to organize my digitized audiobooks collection.
I have a set of folders which I need to write to CDs. The folders can not be split: each folder goes onto one disk.
I want to fill the disks most efficiently:
80 + 20
remaining space is better than 50 + 50
).Which algorithm should I use?
Upvotes: 4
Views: 981
Reputation: 25139
This is called the Bin Packing Problem and is NP-hard, so there is not a simple algorithm to solve it.
The solution I found worked best (I ran a programming contest with a question almost identical to this), was to order the folders by size and put the largest folder that still fits onto the disc until it is full or all remaining folders are too large to fit in the remaining space.
This solves the problem quickly since after the sort the rest of the algorithm is O(n).
In the contest I ran, this resulted in 74 discs instead of the 79 that a naive solution would achieve for our largest test data set.
Upvotes: 4
Reputation: 10843
If you would like to pack files/folders on one CD-R disc, than you could do this optimally in pseudo-polynominal time. To do this, you have to round sizes of files/folders into sectors, and count sectors available on CD-R.
After this, we get discrete 1-D knapsack packing problem, which can be solved nicely using dynamic programming, with complexity O(n),
To be more specific:
For better performance you can always over-approximate size of sectors, example setup:
What's more:
Maybe applying this algorithm in greedy manner "pack one cd, pack next cd" will do it's work?
Upvotes: 2