Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Place random non-overlapping rectangles on a panel

I've a panel of size X by Y. I want to place up to N rectangles, sized randomly, upon this panel, but I don't want any of them to overlap. I need to know the X, Y positions for these rectangles.

Algorithm, anyone?

Edit: All the N rectangles are known at the outset and can be selected in any order. Does that change the procedure?

like image 275
Scott Evernden Avatar asked Apr 04 '09 05:04

Scott Evernden


1 Answers

You can model this by a set of "free" rectangles, starting with single one with coordinates of 0,0, size (x, y). Each time you need to add one more rectangle, choose one of remaining "free" rectangles, generate new rectangle (with top-left coordinate and size such that it will be fully contained), and split that rectangle as well as any other overlapping "free" rectangle, such that children express remaining free space. This will result in 0 to 4 new rectangles (0 if new rectangle was exactly the size of old free rectangle; 4 if it's in the middle and so on). Over time you will get more and more smaller and smaller free areas, so rectangles you create will be smaller as well.

Ok, not a very elaborate explanation, it's easier to show on whiteboard. But the model is one I used for finding starting location for newly cut'n pasted gui components; it's easy to keep track of available chunks of screen, and choose (for example) left or topmost such area.

like image 70
StaxMan Avatar answered Sep 19 '22 08:09

StaxMan