I have an array of rectangles (length and width). Not guaranteed to be square, but always guaranteed to be whole numbers. I want to position the blocks in a coordinate system as efficiently as possible so that the bounding box that contains all elements is as small as possible. I also want to tend toward a square. The variance in terms of size won't be too great, but I'd like a generic algorithm.
I found this somewhat difficult to search for, just 开发者_如何学JAVAlooking for someone to point me in the right direction. Just looking for pseudo-code (language is irrelevant) or a library that could be implemented in Java if need be. Performance is an issue so I really need it to be as efficient as possible in every regard.
Note: If this somehow becomes much easier if I'm restricted to squares only, that might be an option.
The Packing problem article on Wikipedia links to this algorithm, described in this paper - "Optimal Rectangle Packing: Initial Results".
I'm not sure how it compares to the algorithm Mr E pointed to, but once I built a window system, and I needed to store rectangular image pieces off-screen. My method was this:
Think of the storage space as tilted 45 degrees to the left, so you have a V-shaped bin. It has one "valley point", at the very bottom (the origin)
\ /
\ /
\/
Drop one block into it, so the block's bottom corner is at the valley point.
Now, going from left to right, you have two valley points, where you can drop additional blocks. Every time you drop a block into a valley point, you revise the list of valley points.
\ /
\/\/
It does waste space, if you drop a large block into a valley point made by small blocks, so it is better to put in large blocks first, if possible. When you drop a block in, you can choose the valley point that wastes the least space.
As I said, I don't know how it compares to the other algorithms, but it was simple.
精彩评论