That problem statement is a variation of the Knapsack problem. Your initial constraint is the 8.5x11 size and you have an additional constraint of aligning the sides as much as possible. The code I posted does accidentally align the sides of the rectangles, but provides no constraints on the size.
I might play around with it a bit to provide the paper-size constraint, but you'd be better off following the googlinks that others have provided.
Update: You can try the following algorithm to see if it helps:
- Get your paper size
- Get your list of rectangles. Collapse it to (x,y,n) if you don't already have it that way.
- Eliminate all rectangles that cannot fit on the paper. E.g., 1x12 won't fit on 8.5x11, but will fit on 8.5x14
- Reduce the number of rectangles of a given size to the most that can fit on your paper. For example, two 6x11 rectangles cannot fit on the same 8.5x11 piece of paper
- Expand the list of rectangles so that (x,y,n) => (x,y) x n
- Order the remaining rectangles by area, smallest first, then by X, smallest first
- Start tiling in the X direction, filling the Y direction and see what comes out
- Re-order the rectangles by area, then Y (smallest first in both values)
- Repeat, but in the Y direction filling the X direction.
- Repeat the two tilings, swapping each particular rectangle's orientation. (($x, $y) = ($y, $x);) This will result in N! tilings, where N is the total number of rectangles (of all sizes) you're working with
- This problem is O(n!), which is pretty crappy. It's also (at least) NP-hard, so you can't really prove this algorithm will provide the best solution. It might provide a good base for a human to take and improve upon, but that's the best it could possibly do.
------ We are the carpenters and bricklayers of the Information Age. The idea is a little like C++ templates, except not quite so brain-meltingly complicated. -- TheDamian, Exegesis 6 Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.
| [reply] [d/l] |