akonsu
akonsu

Reputation: 29538

random placement of rectangles with no overlaps

I am looking for a sound algorithm that would randomly place a given number of rectangles of the same size into a bigger rectangle (canvas).

I see two ways to do it:

  1. create an empty array that will contain the rectangles already placed on canvas. start with the empty canvas. in a loop, pick a position at random for a new rectangle to be placed. check if the array has a rectangle that overlaps with the new rectangle. if it does not, put the new rectangle in to the array and repeat the loop. otherwise, pick a new position, and rerun the check again. and so on. This might never terminate (theoretically) I think. I do not like it.

  2. use a grid and place rectangles into the cells randomly. This might still look like a grid placement. I do not like it either.

any better ways to do it? "better" meaning more efficient, or more visually "random" than the grid approach. better in any respect.

Upvotes: 3

Views: 4009

Answers (3)

Malcolm McLean
Malcolm McLean

Reputation: 6406

I create internal room-like dungeons using the following method.

1) Scatter N points at random, but not within a few pixels of each other. 2) For each point in turn, expand if possible in all four directions. Cease expanding if you hit another rectangle. 3) Cease the algorithm when no rooms can expand.

The result is N rectancles with just a few rectangular small spaces.

Code is in the binary image library

https://github.com/MalcolmMcLean/binaryimagelibrary/blob/master/dungeongenerator3.c #

Upvotes: 0

delete_this_account
delete_this_account

Reputation: 2446

Here is a simple heuristic. It will be non-overlapping and random.

Place a rectangle randomly. Then, calculate the intersections of extensions of the the two parallel edges of the first rectangle with the edges of the canvas. You will obtain four convex empty regions. Place other rectangles in these empty regions one-by-one independently and calculate the similar divisions for placements. And try to put the remaining rectangles in empty regions.

You can try different strategies. You can try to place the rectangles close to the corners. Or, you can place them around the center of the regions. We cannot discuss optimality because you introduced randomness.

Upvotes: 1

Murat Derya Özen
Murat Derya Özen

Reputation: 2154

You might find Quadtrees or R-trees useful for your purpose.

Upvotes: 0

Related Questions