<p>I am looking for pointers to the solution of the following problem: I have a set of rectangles, whose height is known and x-positions also and I want to pack them in the more compact form. With a little drawing (where all rectangles are of the same width, but the width may vary in real life), i would like, instead of. </p>

<pre><code>-r1-
  -r2--
     -r3--
       -r4-
        -r5--
</code></pre>

<p>something like.</p>

<pre><code>-r1-  -r3-- 
  -r2-- -r4-
         -r5--
</code></pre>

<p>All hints will be appreciated. I am not necessarily looking for "the" best solution.</p>

Something like this?
Sort your collection of rectangles by x-position
write a method that checks which rectangles are present on a certain interval of the x-axis
```
```
Collection<Rectangle> overlaps (int startx, int endx, Collection<Rectangle> rects){
...
}
```
```
loop over the collection of rectangles
```
```
Collection<Rectangle> toDraw;
Collection<Rectangle> drawn;
foreach (Rectangle r in toDraw){
Collection<Rectangle> overlapping = overlaps (r.x, r.x+r.width, drawn);
int y = 0;
foreach(Rectangle overlapRect in overlapping){
y += overlapRect.height;
}
drawRectangle(y, Rectangle);
drawn.add(r);
}
```
```