Aligning overlapping rectangles

I am trying to create a bunch of overlapping rectangles that start like this:

alt text http://img690.imageshack.us/img690/209/picture1bp.png

The 2-pass algorithm I came up with is approximately:

// 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 (possibly) ends with rectangles laid out as: alt text http://img685.imageshack.us/img685/9963/picture2bc.png

This is not aesthetically pleasing, so I thought of a second pass that would move them all, starting again from the very top:

// 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 look like the one shown below (looks exactly in practice):

alt text http://img511.imageshack.us/img511/7059/picture3za.png

, , , , . , ? ?

+3
2

, . , , , , , ( ) . , , .

, .

:

A
A C
A C E
A C E
B C E
B D E
B D F
B D F
  D F
    F

( )

, , . , B , E. , , 2.

:

// Pass 1 - Move all rectangles to the right until they do not overlap any other rectangles
rects = getRectsSortedOnTopLeft(); // topmost first, all rects same width
foreach(rect in rects)
    while(rect.collidingRects())
        rect.x += RECT_WIDTH;
// Pass 2 - Move all rectangles to the leftmost position in which they don't overlap any other rectangles
foreach(rect in rects)
    for(i=LEFT_MARGIN; i+=RECT_WIDTH; i<rect.x)
    {
        o = rect.x;
        rect.x = i;
        if(rect.collidingRects())
            rect.x = o;
    }
+3

, - , :

, , , , , , :)

+2

Source: https://habr.com/ru/post/1727061/


All Articles