The elegant way is via the rectangle packing. The brute force you described would work. Ugly, indeed.