I am trying to layout a bunch of overlapping rectangles that start out like this:
The 2-pass algorithm I thought up is roughly:
// Pass 1 - Move all rectangles to the right until they do not overlap any other rectangles
rects = getRectsSortedOnTopLeft(); // topmost first, all rects same size
foreach(rect in rects)
{
while(rect.collidingRects().size() != 0)
{
rect.x += RECT_SIZE;
}
}
This (probably) ends up with rectangles laid out like:
This is not aesthetically pleasing so I thought of a second pass which would move them all left starting again from the topmost:
// Pass 2
foreach(rect in rects)
{
while(rect.x >= LEFT_MARGIN)
{
assert(rect.collidingRects().size() == 0);
rect.x -= RECT_WIDTH;
if(rect.collidingRects().size() != 0)
{
rect.x += RECT_WIDTH;
break;
}
}
}
I think this should end up looking like below (looks exactly correct in practice):
However, I am wary of this algorithm because I am not sure if it will lay out correctly in all cases and it may be really slow. Do you think this algorithm can work? Can you make some suggestions on a better algorithm?