Search code examples
algorithmoverlaprectanglespacking

How to distribute rectangles with minimum overlap


Basically I need to distribute various rectangles in a bigger rectangle randomly. So:

  1. While there is enough space, rectangles don't overlap or overlap just a bit.
  2. When there is not enough space rectangles overlap but still trying to overlap as little as possible (so they all stack in one place).

I don't need classical ideal top-left to bottom-right packing. The point is that I need random spread.

At first I tried to brute-force it by randomly selecting position for a rectangle and then comparing collision with all rectangles that were already placed. Not ideal, obviously.

Then I tried to assign "points" to the space and place rectangles near these points. The closer rectangle was to a point the more "pressure" it applied to it. And that pressure stacked for each rectangle that was placed. Algorithm tried to place rectangles near points with minimal pressure. Unfortunately this resulted in rectangles stacking near top-left and bottom-right corners.

enter image description here

(If you'll close this one too I don't even know what more info do you need).


Solution

  • Assuming you don't want any overlap you can use method called sweeping to find all possible spots for middle of new rectangle. It can be divided into rectangles, then calculate area of each one and choose one randomly with respective ratios. If that is good solution ask for more details.

    And if they can overlap, let's say 10% then just make rectangles smaller than 10%, distribute them and them inflate back.