Search for free space on the stage

I draw rectangles at random positions on the stage, and I don't want them to overlap. Therefore, for each rectangle I need to find an empty area to place it.

I was thinking about trying a random position, check if he is free with

private function containsRect(r:Rectangle):Boolean {
    var free:Boolean = true;
    for (var i:int = 0; i < numChildren; i++)
        free &&= getChildAt(i).getBounds(this).containsRect(r);
    return free;
}

and in case it returns false, try with a different random position.

The problem is that if there is no free space, I will always be stuck in random positions.

Is there an elegant solution for this?

+3
source share
7 answers

Let S be the area of ​​the scene. Let A be the area of ​​the smallest rectangle we want to draw. Let N = S / A

Possible deterministic approach:

, 4 , . , 4 (), .. N , S - , A - . ( ), , 1 , , . . ( , ​​ , .)

, O (N) ( , ), .

. k, k .

2: , . , O (logN), /S /S. .

  •  
: O (N)
: O (N)

:

. , ( , ), , . , .

, , . , > 1/N < 1-1/N. N . < (1-1/N) ^ N < 1/. , , . , , . Nlog (N) 1/N, N² 1/e ^ N.

: , , NlogN ( N²), , .

: O (NlogN) , O (N²)
: O (1)
+3

. LxH, L , H , , , .

, , . , y ( , ), . x- .

+3

, , . , 100?

, - , "". , tween , " ".

+1

, , , , , . , . , , , , , , , , .

, , !

+1

, , , , - :

-. , 6x4 (3, 2), (3 + 6 * x, 2 + 4 * y). , .

for (x = 0, x < stage.size / rect.width - 1, x++)
    for (y = 0, y < stage.size / rect.height - 1, y++)
        if can_draw_rectangle_at([x,y], [x+rect.width, y+rect.height])
            return true;

, ( ), .

0

, , , - 2D . , .

, . ^ H ^ H ^ H ^ H ^ H ^ H ^ H . , , O (nm), n - , m - . , argh.

Edit2: -, , , , ActionScript, .

0

,

  • N , N - ,
  • , N, .

You can limit how the starting points are deferred if you want to have the minimum allowable rectangle size.

If you want the entire space to be covered with rectangles, you can gradually add random points to the remaining “free” space until an open area is detected.

0
source

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


All Articles